2017-09-01 304 views
-2

使用python,假设string =“Tiësto& Sevenn - BOOM(Artelax Remix)”,它包含非ASCII字符,我如何使用unidecode来修复字符串,以便清除非ascii字符?蟒蛇unidecode - 如何使用

string = random.choice(list(open('data.csv'))).rstrip() 
print "[+] Starting search for:", string 

artistname = string.rsplit(' - ', 1)[0] 
songname = string.rsplit(' - ', 1)[1] 

上述剪断给我: ARTISTNAME =铁斯托& Sevenn SONGNAME = BOOM(Artelax混音)

正如你所看到的,ARTISTNAME仍含有非ASCII字符。我如何使用unidecode来解决这个问题?

+2

你看过[使用示例](https://pypi.python.org/pypi/Unidecode)?你有没有试图弄清楚如何使用unidecode? – user2357112

+0

你到目前为止尝试过什么?你想删除它们还是替换它们?在你的例子中,你想要'Tiesto&Sevenn'或者'Tisto&Sevenn'或者其他什么吗? –

+0

是的。我试过unidecode(u'string')。我希望将字符更改为e,而不是将它们一起删除。 – god

回答

2

只需拨打unidecode在您的字符串(加引号):

>>> from unidecode import unidecode 
>>> unidecode(string) 
'Tiesto & Sevenn - BOOM (Artelax Remix)' 

还有归成分解形式之后除去组合字符的长/慢路线:

>>> import unicodedata 
>>> ''.join(s for s in unicodedata.normalize('NFD', string) if not unicodedata.combining(s)) 
'Tiesto & Sevenn - BOOM (Artelax Remix)' 
+1

unidecode(string)---这会引发异常或警告,因为我的data.csv文件中的某些字符串很适合去,而且不需要通过unidecode进行转换。 /usr/lib64/python2.7/site-packages/unidecode/__init__.py:46:RuntimeWarning:参数不是一个unicode对象。传递编码的字符串可能会有意想不到的结果。 清理我的data.csv文件中的所有非ascii字符与我拔出字符串时会更有意义吗? – god

+1

@god:在清理它之前,你需要实际上读取数据*为unicode *。使用['codecs.open'](https://docs.python.org/3/library/codecs.html#codecs.open),并指定正确的编码。 – user2357112