2017-09-01 302 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