python轉碼時出現'illegal multibyte sequen'錯誤

在Python中,能夠對String調用decode和encode方法來實現轉碼。python

好比,若要將某個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.code

相關文章
相關標籤/搜索