解决文件中unicode输入字符串与unicode数据的比较

时间:2015-08-15 13:08:00

标签: python unicode

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"
  

回溯(最近一次调用最后一次):文件“”,第3行,in   UnicodeDecodeError:'ascii'编解码器无法解码字节0xe0的位置   0:序数不在范围内(128)

在文本文件中,我有大量的尼泊尔unicode。

我在这里做错了比较两个unicode字符串吗?

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

1 个答案:

答案 0 :(得分:3)

您的string1字节字符串,编码为UTF-8。 不是 Unicode字符串。但是您使用codecs.open()将Python 解码文件内容发送到unicode。然后尝试将字节字符串与包含测试一起使用会导致Python将字节字符串隐式解码为unicode以匹配类型。由于隐式解码使用ASCII,因此失败。

首先将string1解码为unicode

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

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

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

请注意开始时的u