Python转码问题的解决方法

yipeiwu_com5年前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.

相关文章

python中的插值 scipy-interp的实现代码

python中的插值 scipy-interp的实现代码

具体代码如下所示: import numpy as np from matplotlib import pyplot as plt from scipy.interpolate im...

python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)

python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)

python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换) Python3 JSON 数据解析...

利用Opencv中Houghline方法实现直线检测

利用Opencv中Houghline方法实现直线检测

利用Opencv中的Houghline方法进行直线检测—python语言 这是给Python部落翻译的文章,请在这里看原文。 在图像处理中,霍夫变换用来检测任意能够用数学公式表达的形状,...

Python中生成Epoch的方法

在Python2中datetime对象没有timestamp方法,不能很方便的生成epoch,现有方法没有处理很容易导致错误。关于Epoch可以参见时区与Epoch 0 Python中生...

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

一、用默认设置绘制折线图 import matplotlib.pyplot as plt x_values=list(range(11)) #x轴的数字是0到10这11个整数 y...