将包含unicodes的Pandas字符串列转换为ascii以加载URL

时间:2018-06-13 12:43:30

标签: python pandas wikipedia-api python-unicode

我有一个pandas DataFrame,其中包含一个包含Wikipedia网址的列,我想加载它。但是,有些字符串不会加载,因为它们包含unicodes。例如,' Kruskal %E2%80%93 Wallis_one-way_analysis_of_variance'提出以下

PageError: Page id "Cauchy%E2%80%93Schwarz_inequality" does not match any      pages. Try another id!

有没有办法将所有unicodes变成ascii?所以在这种情况下,我需要一个可以创建新列的函数:

old column                            new column
Cauchy%E2%80%93Schwarz_inequality     Cauchy–Schwarz_inequality
Markov%27s_inequality                 Markov's_inequality

1 个答案:

答案 0 :(得分:1)

urllib.parse.unquote应该做到这一点。希望这会有所帮助。

In [1]: import urllib
   ...: 
   ...: import pandas as pd
   ...: 
   ...: 
   ...: df = pd.DataFrame({'url': ['Markov%27s_inequality', 'Cauchy%E2%80%93Schwarz_inequality']})
   ...: df['clean_url'] = df['url'].apply(urllib.parse.unquote)
   ...: 

In [2]: df
Out[2]: 
                                 url                  clean_url
0              Markov%27s_inequality        Markov's_inequality
1  Cauchy%E2%80%93Schwarz_inequality  Cauchy–Schwarz_inequality