UnicodeDecodeError:“utf-8”编解码器无法解码位置 34 中的字节 0xe3:无效的连续字节

2024-03-27

我想用以下代码在 python 文件中打开一些波斯语文本文件:

 for line in codecs.open('0001.txt',encoding='UTF-8'):
       lines.appends(line)

但它给了我这个错误:

> Traceback (most recent call last):
  File "/usr/lib/pycharm-community/helpers/pydev/pydevd.py", line 1596, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/usr/lib/pycharm-community/helpers/pydev/pydevd.py", line 974, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/usr/lib/pycharm-community/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/nlpuser/Documents/ms/Work/General_Dataset_creator/BijanKhanReader.py", line 24, in <module>
    for lin in codecs.open('corpuses/markaz/0001.txt',encoding='UTF-8'):
  File "/home/nlpuser/anaconda3/envs/tmpy36/lib/python3.6/codecs.py", line 713, in __next__
    return next(self.reader)
  File "/home/nlpuser/anaconda3/envs/tmpy36/lib/python3.6/codecs.py", line 644, in __next__
    line = self.readline()
  File "/home/nlpuser/anaconda3/envs/tmpy36/lib/python3.6/codecs.py", line 557, in readline
    data = self.read(readsize, firstline=True)
  File "/home/nlpuser/anaconda3/envs/tmpy36/lib/python3.6/codecs.py", line 503, in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe3 in position 0: invalid continuation byte

这段代码有什么问题?

他是 file 的输出:

0001.txt:非 ISO 扩展 ASCII 文本,带有 CRLF 行终止符


UTF-8 具有非常特定的格式,因为字符可以由 1 到 4 个字节的任意位置表示。

如果一个字符是单字节,它将表示为0x00-0x7F。如果用它来表示two或更多,则leading字节将以0xC2 to 0xF4,然后是一到三个延续字节,范围为0x80 to 0xBF.

在你的例子中,Python 发现了一个位于连续字符位置的字符(即前导字符后面的字符之一),但是0xE3,这不是合法的延续字符。问题可能出在您的文本文件中,而不是您的程序中 - 要么编码错误,要么编码错误。

Use hexdump -C <file> or xxd <file>验证您拥有的确切字节序列以及file <file>尝试猜测编码,我们也许可以说更多。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

UnicodeDecodeError:“utf-8”编解码器无法解码位置 34 中的字节 0xe3:无效的连续字节 的相关文章

随机推荐