'utf8' codec can't decode byte 0xd1 in position 931: invalid continuation byte解決方法


有時候,我得到這樣的字符œ導致的UnicodeDecodeError錯誤。

我需要能夠使串的UTF-8有或沒有這些字符。

 

在工作中,經常遇到,讀取一個文件,或者是從網頁獲取一個問題,明明看着是gb2312的編碼,可是當使用decode轉時,總是出錯,這個時候, 可以使用decode(‘gb18030′)這個字符集來解決,如果還是有問題,這個時候,一定要注意,decode還有一個參數,比如,若要將某個 String對象s從gbk內碼轉換為UTF-8,可以如下操作
s.decode(‘gbk’).encode(‘utf-8′)
可是,在實際開發中,我發現,這種辦法經常會出現異常:
UnicodeDecodeError: ‘gbk’ codec can’t decode bytes in position 30664-30665: illegal multibyte sequence
這 是因為遇到了非法字符——尤其是在某些用C/C++編寫的程序中,全角空格往往有多種不同的實現方式,比如\xa3\xa0,或者\xa4\x57,這些 字符,看起來都是全角空格,但它們並不是“合法”的全角空格(真正的全角空格是\xa1\xa1),因此在轉碼的過程中出現了異常。
這樣的問題很讓人頭疼,因為只要字符串中出現了一個非法字符,整個字符串——有時候,就是整篇文章——就都無法轉碼。
解決辦法:
s.decode(‘gbk’, ‘ignore’).encode(‘utf-8′)
因為decode的函數原型是decode([encoding], [errors='strict']),可以用第二個參數控制錯誤處理的策略,默認的參數就是strict,代表遇到非法字符時拋出異常;
如果設置為ignore,則會忽略非法字符;
如果設置為replace,則會用?取代非法字符;
如果設置為xmlcharrefreplace,則使用XML的字符引用。

python文檔

decode( [encoding[, errors]])
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is ’strict’, meaning that encoding errors raise UnicodeError. Other possible values are ‘ignore’, ‘replace’ and any other name registered via codecs.register_error, see section 4.8.1.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM