2015-08-15 30 views
0
string1=" म नेपाली हुँ" 
string1=string1.split() 
string1[0] 
'\xe0\xa4\xae' 

with codecs.open('nepaliwords.txt','r','utf-8') as f: 
    for line in f: 
      if string1[0] in line: 
        print "matched string found in file" 

Traceback (most recent call last): File "", line 3, in UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)解決的unicode輸入字符串的文件中使用Unicode數據

在文本文件中的比較,我有大量尼泊爾的Unicode的。

我在這裏比較兩個unicode字符串做錯了嗎?

如何打印匹配的unicode字符串?

回答

3

您的string1字節字符串,編碼爲UTF-8。它是而不是一個Unicode字符串。但是您使用codecs.open()將Python 解碼爲的文件內容爲unicode。試圖將您的字節字符串用於包含測試會導致Python將字節字符串隱式解碼爲unicode以匹配類型。由於隱式解碼使用ASCII,因此這會失敗。

解碼string1unicode第一:

string1 = " म नेपाली हुँ" 
string1 = string1.decode('utf8').split()[0] 

或使用的Unicode字符串文字來代替:

string1 = u" म नेपाली हुँ" 
string1 = string1.split()[0] 

注意u在開始。

+0

謝謝string1 = u「मनेपालीहुँ」解決了我的情況。對於string1 = string1.split()[0] [0]創建的問題..謝謝 –

+0

你能幫我打印匹配的字符串嗎? –