def robust_decode(bs):
'''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
cr = None
try:
cr = bs.decode('utf8')
except UnicodeDecodeError:
cr = bs.decode('latin1')
return cr
Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.
当您得到一个
UnicodeEncodeError
时,这意味着在代码中的某个地方,您可以直接将字节字符串转换为unicode字符串。默认情况下,在Python 2中它使用ascii编码,在Python3中使用utf8编码(这两种编码都可能失败,因为不是每个字节在两种编码中都有效)为了避免这种情况,必须使用显式解码。
如果输入文件中可能有两种不同的编码,其中一种接受任何字节(如UTF8和Latin1),则可以尝试先将字符串转换为first,如果发生UnicodeDecodeError,则使用第二种编码。
如果不知道原始编码并且不关心非ascii字符,可以将
decode
方法的可选errors
参数设置为replace
。任何有问题的字节都将被替换(从标准库文档中):当我在python3中执行时出现了这个错误,我只需在
python2
中执行就可以得到相同的程序您正在编码到UTF-8,然后re-编码到UTF-8。Python只有先将解码为Unicode时才能执行此操作,但它必须使用默认的ASCII编解码器:
不要继续编码;将编码留给UTF-8直到最后一个可能的时刻。改为连接Unicode值。
您可以在这里使用
str.join()
(或者,更确切地说,使用unicode.join()
)将这三个值与中间的破折号连接起来:但即使在这里编码也可能为时过早。
经验法则:解码接收到值的时刻(如果不是API已经提供的Unicode值),仅在必须时编码(如果目标API不直接处理Unicode值)。
相关问题 更多 >
编程相关推荐