文章内容
2017/9/19 12:28:42,作 者: 黄兵
Python中转码错误遇到 illegal multibyte sequence
当调用如下语句:
- re_data = re_data.decode('gbk') #re_data 是#-*- coding: cp936 -*-类型字符串,即gbk编码
如果字符串中有非法字符,有时会报错,抛出如下异常:
'gbk' codec can't decode bytes in position 19566-19567: illegal multibyte sequence
解决思路,把相应的非法字符删掉。一个字符串中可能会多次遇到非法字符,所以用了递归。如下为转码函数:
- def transformCodec(re_data):#ascii (gbk) 转 unicode
- try:
- re_data = re_data.decode('gbk')
- except Exception as error:
- print error
- print 'delete illegal string,try again...'
- pos = re.findall(r'decodebytesinposition([\d]+)-([\d]+):illegal',str(error).replace(' ',''))
- if len(pos)==1:
- re_data = re_data[0:int(pos[0][0])]+re_data[int(pos[0][1]):]
- re_data = transformCodec(re_data)
- return re_data
- return re_data
调用:
- re_data = transformCodec(re_data) #转码
可能方法比较笨,如果谁有更好的方法,欢迎留言告知。
评论列表