让Python默认用字符串替换无法编码的字符

8 投票
3 回答
7805 浏览
提问于 2025-04-15 17:12

我想让Python在遇到无法编码的字符时,直接把它们替换成字符串 "<could not encode>",这样就不会出错了。

比如,假设默认的编码方式是ascii,那么执行下面的命令

'%s is the word'%'ébác'

就会得到

'<could not encode>b<could not encode>c is the word'

有没有办法让这个行为在我整个项目中都默认生效呢?

3 个回答

5

比如说:

>>> help("".encode)
Help on built-in function encode:

encode(...)
S.encode([encoding[,errors]]) -> object

Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. **Other possible values are** 'ignore', **'replace'** and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that is able to handle UnicodeEncodeErrors.

你可以给codecs.register_error添加自己的回调函数,这样就可以用你想要的字符串来替换错误信息。

>>> x
'\xc3\xa9b\xc3\xa1c is the word'
>>> x.decode("ascii")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
>>> x.decode("ascii", "replace")
u'\ufffd\ufffdb\ufffd\ufffdc is the word'
11

str.encode 这个函数可以接受一个可选的参数,用来定义如何处理错误:

str.encode([encoding[, errors]])

根据文档:

这个函数会返回一个编码后的字符串。默认的编码方式是当前的默认字符串编码。你可以通过设置错误参数来选择不同的错误处理方式。默认的错误处理方式是 'strict',这意味着如果编码出错,会抛出一个 UnicodeError。其他可能的选项有 'ignore'(忽略错误)、'replace'(替换错误)、'xmlcharrefreplace'(用 XML 字符引用替换)、'backslashreplace'(用反斜杠替换)以及通过 codecs.register_error 注册的任何其他名称,具体可以参考 Codec 基类部分。想查看可能的编码方式,可以查阅标准编码部分。

在你的情况下,codecs.register_error 函数可能会对你有帮助。

[关于 坏字符 的说明]

顺便提一下,当使用 register_error 时,你可能会发现自己不仅仅是在替换单个坏字符,而是会把一组连续的坏字符替换成你的字符串,除非你特别注意。每次遇到坏字符时,你只会调用一次错误处理器,而不是每个字符都调用一次。

撰写回答