<p>您可以定义自己的自定义处理程序,并使用它来做您想做的事。请参见以下示例:</p>
<pre class="lang-py prettyprint-override"><code>import codecs
from logging import getLogger
log = getLogger()
def custom_character_handler(exception):
log.error("%s for %s on %s from position %s to %s. Using '?' in-place of it!",
exception.reason,
exception.object[exception.start:exception.end],
exception.encoding,
exception.start,
exception.end )
return ("?", exception.end)
codecs.register_error("custom_character_handler", custom_character_handler)
print( b'F\xc3\xb8\xc3\xb6\xbbB\xc3\xa5r'.decode('utf8', 'custom_character_handler') )
print( codecs.encode(u"abc\u03c0de", "ascii", "custom_character_handler") )
</code></pre>
<p>运行它,您将看到:</p>
^{pr2}$
<p>参考文献:</p>
<ol>
<li><a href="https://docs.python.org/3/library/codecs.html#codecs.register_error" rel="nofollow noreferrer">https://docs.python.org/3/library/codecs.html#codecs.register_error</a></li>
<li><a href="https://docs.python.org/3/library/exceptions.html#UnicodeError" rel="nofollow noreferrer">https://docs.python.org/3/library/exceptions.html#UnicodeError</a></li>
<li><a href="https://stackoverflow.com/questions/20624144/how-to-ignore-invalid-lines-in-a-file">How to ignore invalid lines in a file?</a></li>
<li><a href="https://stackoverflow.com/questions/28583565/str-object-has-no-attribute-decode-python-3-error">'str' object has no attribute 'decode'. Python 3 error?</a></li>
<li><a href="https://stackoverflow.com/questions/38564456/how-to-replace-invalid-unicode-characters-in-a-string-in-python">How to replace invalid unicode characters in a string in Python?</a></li>
<li><a href="https://stackoverflow.com/questions/24616678/unicodedecodeerror-in-python-when-reading-a-file-how-to-ignore-the-error-and-ju">UnicodeDecodeError in Python when reading a file, how to ignore the error and jump to the next line?</a></li>
</ol>