Python编解码器错误除外?

Dee*_*pak 3 python encode decode

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
Run Code Online (Sandbox Code Playgroud)

嗨,我得到了这个例外.如何捕获它,并在我收到此异常时继续读取我的文件.

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

以下不起作用

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

小智 6

请查看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')
Run Code Online (Sandbox Code Playgroud)