在python中设置隐式默认编码\解码错误处理

2024-05-19 01:41:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理用拉丁文编码的外部数据。所以我添加了sitecustomize.py,并在其中添加了

sys.setdefaultencoding('latin_1') 

当然,现在使用拉丁1字符串可以很好地工作。在

但是,万一我遇到一些不是拉丁语编码的东西:

^{pr2}$

我得到UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2013' in position 3: ordinal not in range(256)

我想要的是,不可编码的字符将被忽略,也就是说,我将在上面的示例s=='abc?'中得到它,并且每次都不显式地调用decode()或{},即在每次调用时不显式地调用s.decode(…,'replace')。在

我试着用codecs.register_error做不同的事情,但是没有用。在

请帮忙?在


Tags: 数据字符串inpy编码syscancodec
2条回答

脚本不能调用是有原因的sys.setdefaultencoding. 不要这样做,有些库(包括Python附带的标准库)希望默认值为“ascii”。在

相反,在读入程序时(通过文件、stdin、socket等)显式地将字符串解码为Unicode,并在写出字符串时显式地对字符串进行编码。在

显式解码采用一个参数,指定不可编码字节的行为。在

您可以定义自己的自定义处理程序,并使用它来做您想做的事。请参见以下示例:

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") )

运行它,您将看到:

^{pr2}$

参考文献:

  1. https://docs.python.org/3/library/codecs.html#codecs.register_error
  2. https://docs.python.org/3/library/exceptions.html#UnicodeError
  3. How to ignore invalid lines in a file?
  4. 'str' object has no attribute 'decode'. Python 3 error?
  5. How to replace invalid unicode characters in a string in Python?
  6. UnicodeDecodeError in Python when reading a file, how to ignore the error and jump to the next line?

相关问题 更多 >

    热门问题