1. 程式人生 > >錯誤:UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode的解決方案

錯誤:UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode的解決方案

執行環境 python2.7
【情景】
最近搞文字處理,遇到了很多編碼問題。chardet是個好東西,封裝了對編碼格式的檢測。通過返回的編碼格式對文字進行解碼/編碼操作,也比較方便。當然,這裡也遇到了一點小問題,當時,從檔案中提取的一個單詞放入chardet.detect()的函式,結果輸出了一片警告。程式碼是能順利執行,但是標準輸出十分難看。
【錯誤警告】
/usr/lib/python2.7/dist-packages/chardet/universaldetector.py:69: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
  if aBuf[:3] == '\xEF\xBB\xBF': /usr/lib/python2.7/dist-packages/chardet/universaldetector.py:72: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal   elif aBuf[:4] == '\xFF\xFE\x00\x00': /usr/lib/python2.7/dist-packages/chardet/universaldetector.py:75: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
  elif aBuf[:4] == '\x00\x00\xFE\xFF': /usr/lib/python2.7/dist-packages/chardet/universaldetector.py:78: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal   elif aBuf[:4] == '\xFE\xFF\x00\x00': /usr/lib/python2.7/dist-packages/chardet/universaldetector.py:81: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
  elif aBuf[:4] == '\x00\x00\xFF\xFE': /usr/lib/python2.7/dist-packages/chardet/universaldetector.py:84: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal   elif aBuf[:2] == '\xFF\xFE': /usr/lib/python2.7/dist-packages/chardet/universaldetector.py:87: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal   elif aBuf[:2] == '\xFE\xFF':
【解決方案】
 可以簡單翻一下警告:
uncode編碼警告:在unicode等價比較中,把兩個引數同時轉換為unicode編碼失敗。中斷並認為他們不相等。
python裡一般處理的是unicode和str的文字物件,經過偵測,傳給chardet的文字是“ascii”的的格式,所以傳給chardet前先轉成unicode的就好了。
另外,python程式本身的utf-8個是編碼,str物件的文字轉換為unicode需要使用text.decode("utf-8").

P·S:祝所有勵志今年“馬上找到呂盆友”的兄弟,恩,還有姐妹們,加油~