Python unicode相等比较失败

2024-04-19 07:27:43 发布

您现在位置:Python中文网/ 问答频道 /正文

此问题链接到Searching for Unicode characters in Python

我使用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字符串比较方法吗?


Tags: to字符串intxtforsearching链接编解码器
1条回答
网友
1楼 · 发布于 2024-04-19 07:27:43

您可以使用==运算符比较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编码。这可能是因为您(程序员)不知道哪个变量保存unicide,哪个变量保存UTF8,哪个变量保存从文件读取的字节。

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

相关问题 更多 >