在实际操作中,将一个dict数据类型中的值,与从Excel表中提取的一系列数据进行比较,看dict中的数据是否与Excel匹配。可能会遇到如下问题:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
出现这个错误后,字符串无法正确匹配,便会出现找不到匹配项的结果。
部分相关代码为:
<p><span style="font-size:18px;">import xlrd</span></p><p></p><p style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size:18px;">bk=xlrd.open_workbook(str_file)</span></p><p style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size:18px;">sh=bk.sheet_by_index(0)</span></p><p style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size:18px;">n=sh.nrows</span></p>
<span style="font-size:18px;">flag=0
for i in range(n):
str1=sh.row(i)[0].value
str2=sh.row(i)[1].value
if(dict1['no']==str1):
if(dict1['name']==str2):
print "Your input 'no':%s,'name':'%s' is right." %(dict1['no'],dict1['name'])
flag=1</span>
<span style="font-size:18px;">if(flag==0):
print "Your input 'no':%s is not exist." % dict1['no']</span>
type(dict1['name']是str,而type(str1)是unicode。
解决办法为:
将
<span style="font-size:18px;"> if(dict1['no']==str1):
if(dict1['name']==str2):</span>
改为
<span style="font-size:18px;"> if(dict1['no']==str1.encode('utf8')):
if(dict1['name']==str2.encode('utf8')):</span>
即可解决字符串转换问题。将unicode码转换成utf8。
该解决方法在本人实际操作中验证可行。仅供参考。