如何修复此警告:UnicodeWarning:Unicode等于比较失败

时间:2017-11-23 07:44:33

标签: python python-2.7 unicode

当我运行代码时,我收到警告,我有两次警告:

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal位于if result2=b and c == 'Pass':

事情正在进行,因为我使用if result2=b and c == 'Pass':三次,只有最后两次有警告。我在Internet上找不到一些解决方案,但它们不能用于我的代码。这是我的代码,请帮助我。 Thx in advanced!

def XXX1():
    XXXXXX
    if result2==b and c == 'Failed':       ----------no warning
    XXXXXX

def XXX2():
    XXXXXX
    if result2==b and c == 'Failed':       ----------warning
    XXXXXX

def XXX3():
    XXXXXX
    if result2==b and c == 'Pass':         ----------warning
    XXXXXX

某些参数可能有所帮助:

with open('1.csv','rb') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['Case Id']== 'getpropertyvalue_without_propertyname' :
            a=row['Result Link']
            c=row['Status']


url = a
html = requests.get(url,verify=False).text
soup = BeautifulSoup(html,'html.parser')

result = soup.find("p", {"class":"ERRORLevel"})
result2=result.text

1 个答案:

答案 0 :(得分:1)

您正在混合Unicode字符串和字节串。 Python 2将在进行比较时尝试解码字节串(作为ASCII),当失败时,您将收到警告:

>>> u'å', u'å'.encode('utf8')
(u'\xe5', '\xc3\xa5')
>>> 'å' == u'å'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

不要混合Unicode字符串和字节串。尽早解码文本数据,并仅比较Unicode对象。在上面的示例中,bytestring是UTF-8编码的,因此首先解码为UTF-8将解决警告。

对于您的示例代码,BeautifulSoup(正确)生成Unicode文本。您必须解码CSV数据,请参阅Read and Write CSV files including unicode with Python 2.7了解解决方案,或使用str.decode()来手动解码这两个字符串。