Python unicode等同比较失败

Cha*_*gaD 58 python unicode

此问题与在Python中搜索Unicode字符相关联

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

codecs.open('story.txt', 'rb', 'utf-8-sig')
Run Code Online (Sandbox Code Playgroud)

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

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
Run Code Online (Sandbox Code Playgroud)

是否有任何特殊的unicode字符串比较方式?

Rob*_*obᵩ 79

您可以使用==运算符来比较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
>>> 
Run Code Online (Sandbox Code Playgroud)

但是,您的错误消息表明您没有比较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
Run Code Online (Sandbox Code Playgroud)

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

我想你的程序是将unicode对象与str对象进行比较,str对象的内容不是有效的UTF8编码.这似乎可能是你(程序员)不知道哪个变量无效,哪个变量保存UTF8以及哪个变量保存从文件读入的字节的结果.

我推荐http://nedbatchelder.com/text/unipain.html,特别是建议创建"Unicode三明治".

  • 'u'Hello'=='\ xc3\x81'`是有效的UTF-8,仍然会发出警告.在Python 2上,默认编解码器是`ascii`. (2认同)