Python unicode相等比较失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18193305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python unicode equal comparison failed
提问by ChamingaD
This question is linked to Searching for Unicode characters in Python
这个问题链接到在 Python 中搜索 Unicode 字符
I read unicode text file using python codecs
我使用 python 编解码器读取 unicode 文本文件
codecs.open('story.txt', 'rb', 'utf-8-sig')
And was trying to search strings in it. But i'm getting the following warning.
并试图在其中搜索字符串。但我收到以下警告。
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
Is there any special way of unicode string comparison ?
unicode 字符串比较有什么特殊的方法吗?
采纳答案by Rob?
You may use the ==
operator to compare unicode objects for equality.
您可以使用==
运算符来比较 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
>>>
But, your error message indicates that you aren'tcomparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
但是,您的错误消息表明您没有比较 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
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
看看我是如何尝试将 unicode 对象与不代表有效 UTF8 编码的字符串进行比较的。
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
我想您的程序正在将 unicode 对象与 str 对象进行比较,并且 str 对象的内容不是有效的 UTF8 编码。这似乎是因为您(程序员)不知道哪个变量保存 unicide,哪个变量保存 UTF8,哪个变量保存从文件中读取的字节。
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
我推荐http://nedbatchelder.com/text/unipain.html,尤其是创建“Unicode Sandwich”的建议。