Python unicode相等比较失败


问题内容

该问题与在Python中搜索Unicode字符有关

我使用python编解码器读取unicode文本文件

codecs.open('story.txt', 'rb', 'utf-8-sig')

并试图在其中搜索字符串。但是我收到以下警告。

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

unicode字符串比较有什么特殊的方法吗?


问题答案:

您可以使用==运算符比较unicode对象是否相等。

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>

但是,您的错误消息表明您 没有 比较unicode对象。您可能正在将一个unicode对象与一个str对象进行比较,如下所示:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

了解我如何尝试将unicode对象与不代表有效UTF8编码的字符串进行比较。

我想您的程序正在将unicode对象与str对象进行比较,而str对象的内容不是有效的UTF8编码。这似乎是您(程序员)不知道哪个变量保存非杀虫剂,哪个变量保存UTF8以及哪个变量保存从文件读取的字节的结果。

我建议使用http://nedbatchelder.com/text/unipain.html,尤其是有关创建“
Unicode三明治”的建议。