python - 除了 Python 编解码器错误?

标签 python decode encode

File "/usr/lib/python3.1/codecs.py", line 300, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 805: invalid start byte

你好,我得到这个异常。我如何捕获它,并在遇到此异常时继续读取我的文件。

我的程序有一个循环,它逐行读取文本文件并尝试进行一些处理。但是,我遇到的一些文件可能不是文本文件,或者包含格式不正确的行(外语等)。我想忽略这些行。

以下是无效的

for line in sys.stdin:
   if line != "":
      try:
         matched = re.match(searchstuff, line, re.IGNORECASE)
         print (matched)
      except UnicodeDecodeError, UnicodeEncodeError:
         continue

最佳答案

http://docs.python.org/py3k/library/codecs.html .当您打开编解码器流时,您可能想要使用附加参数 errors='ignore'

在 Python 3 中,sys.stdin 默认情况下作为文本流打开(参见 http://docs.python.org/py3k/library/sys.html ),并且具有严格的错误检查。

您需要将其重新打开为容错的 utf-8 流。这样的事情会起作用:

sys.stdin = codecs.getreader('utf8')(sys.stdin.detach(), errors='ignore')

关于python - 除了 Python 编解码器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4554287/

相关文章:

Python - 查找字符串中字符串列表第一次出现的索引位置

Python Pandas : Selecting previous row of matching row

python - python中的JSON模式转换

Javascript解码URI会出现问题

python - 如何使用 python 解码 utf 16 中存在的字符串

file - 使用 Python 3 和 unicode 写入文件

python - python中的字典理解太全面了

camera - QR码(二维条码)编码和解码算法?

c++ - 使用 CBOR 编码和解码时出现问题

使用 HMAC-SHA256 的 Python 编码消息