文章内容

2017/9/19 12:28:42,作 者: 黄兵

Python中转码错误遇到 illegal multibyte sequence

当调用如下语句:

  1. re_data = re_data.decode('gbk'#re_data 是#-*- coding: cp936 -*-类型字符串,即gbk编码  

如果字符串中有非法字符,有时会报错,抛出如下异常:

'gbk' codec can't decode bytes in position 19566-19567: illegal multibyte sequence


解决思路,把相应的非法字符删掉。一个字符串中可能会多次遇到非法字符,所以用了递归。如下为转码函数:

  1. def transformCodec(re_data):#ascii (gbk) 转 unicode  
  2.     try:  
  3.         re_data = re_data.decode('gbk')  
  4.     except Exception as error:  
  5.         print error  
  6.         print 'delete illegal string,try again...'  
  7.           
  8.         pos = re.findall(r'decodebytesinposition([\d]+)-([\d]+):illegal',str(error).replace(' ',''))  
  9.         if len(pos)==1:  
  10.             re_data = re_data[0:int(pos[0][0])]+re_data[int(pos[0][1]):]  
  11.             re_data = transformCodec(re_data)  
  12.             return re_data  
  13.     return re_data  

调用:

  1. re_data = transformCodec(re_data) #转码  

可能方法比较笨,如果谁有更好的方法,欢迎留言告知。

本文转载自:CSDN - 深水技术宅 Python中转码错误遇到 illegal multibyte sequence

分享到:

发表评论

评论列表