Python unicode 相等比较失败

标签 python unicode

此问题链接到 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字符串比较有什么特殊的方法吗?

最佳答案

您可以使用 == 运算符来比较 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 三明治”的建议。

关于Python unicode 相等比较失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18193305/

相关文章:

python - SSL: CERTIFICATE_VERIFY_FAILED] 从 python 脚本生成 SMS 时证书验证失败

python - 在 dask.array.map_blocks [OpenCV, Dask] 中调用并返回 cv2.cvtColor

c++ - 使用 UTF8CPP 时如何检测空格或数字?

c# - 使用 C# 检测文件名字符是否被认为是国际化的

mysql - UTF-8字符有问题;我看到的不是我存储的

python - GAE : TypeError: character mapping must return integer, 无或 unicode

python - Django不能上传文件和图片

python - 使用 python 和 gmail 在同一个线程中发送多封电子邮件

python - Flask-登录重置 MongoDB 密码 - 查询不起作用

python 瓶 : UTF8 path string invalid when using app. mount()