让python默认用字符串替换不可编码的字符

问题描述 投票:0回答:3

我想让Python忽略它无法编码的字符,只需将它们替换为字符串

"<could not encode>"

例如,假设默认编码是 ascii,则命令

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

会产生

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

有什么方法可以使其成为我所有项目的默认行为吗?

python replace encode
3个回答
11
投票

str.encode
函数采用一个可选参数来定义错误处理:

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

来自文档:

返回字符串的编码版本。默认编码是当前默认的字符串编码。可以给出错误来设置不同的错误处理方案。错误的默认值是“strict”,这意味着编码错误会引发 UnicodeError。其他可能的值包括“ignore”、“replace”、“xmlcharrefreplace”、“backslashreplace”以及通过 codecs.register_error() 注册的任何其他名称,请参阅编解码器基类部分。有关可能的编码的列表,请参阅标准编码部分。

在您的情况下,

codecs.register_error
函数可能会令人感兴趣。

[注意坏字符]

顺便说一句,请注意,在使用

register_error
时,您可能会发现自己不仅用字符串替换了单个坏字符,而且还替换了一组连续的坏字符,除非您注意。每次运行错误字符(而不是每个字符)时,您都会调用一次错误处理程序。


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.

所以,例如:

>>> 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'

将您自己的回调添加到 codecs.register_error 以替换为您选择的字符串。


0
投票

codecs.register_error的最小示例

#!/usr/bin/env python3 import codecs def some_handler(exception): return (b"-", exception.end) codecs.register_error("some_handler", some_handler) s = '\uff1a' _bytes = s.encode("latin1", errors="some_handler") print(repr(_bytes)) # b'-'
    
© www.soinside.com 2019 - 2024. All rights reserved.