gpt4 book ai didi

UnicodeDecodeError : unexpected end of data

转载 作者:行者123 更新时间:2023-12-04 03:52:15 27 4
gpt4 key购买 nike

我有一个巨大的文本文件,我想打开它。
我正在分块读取文件,避免与一次读取过多文件相关的内存问题。

代码片段:

def open_delimited(fileName, args):

with open(fileName, args, encoding="UTF16") as infile:
chunksize = 10000
remainder = ''
for chunk in iter(lambda: infile.read(chunksize), ''):
pieces = re.findall(r"(\d+)\s+(\d+_\d+)", remainder + chunk)
for piece in pieces[:-1]:
yield piece
remainder = '{} {} '.format(*pieces[-1])
if remainder:
yield remainder

代码抛出错误 UnicodeDecodeError: 'utf16' codec can't decode bytes in position 8190-8191: unexpected end of data .

我试过 UTF8并得到错误 UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte .
latin-1iso-8859-1引发错误 IndexError: list index out of range
输入文件示例:
b'\xff\xfe1\x000\x000\x005\x009\x00\t\x001\x000\x000\x005\x009\x00_\x009\x007\x004\x007\x001\x007\x005\x003\x001\x000\x009\x001\x00\t\x00\t\x00P\x00o\x00s\x00t\x00\t\x001\x00\t\x00H\x00a\x00p\x00p\x00y\x00 \x00B\x00i\x00r\x00t\x00h\x00d\x00a\x00y\x00\t\x002\x000\x001\x001\x00-\x000\x008\x00-\x002\x004\x00 \x00'

我还将提到我有几个这样的巨大文本文件。 UTF16它们中的许多都可以正常工作,但在特定文件中失败。

无论如何要解决这个问题?

最佳答案

要忽略损坏的数据(可能导致数据丢失),请设置 errors='ignore'open()称呼:

with open(fileName, args, encoding="UTF16", errors='ignore') as infile:

open() function documentation状态:

  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.


这并不意味着您可以从遇到的明显数据损坏中恢复。

为了说明这一点,想象一个字节被删除或添加到您的文件中的某处。 UTF-16 是一种编解码器,每个字符使用 2 个字节。如果有一个字节丢失或剩余,则丢失或额外字节之后的所有字节对都将不对齐。

这可能会导致进一步解码的问题,不一定是立即解码。 UTF-16 中有一些代码点是非法的,但通常是因为它们与另一个字节对组合使用;对于这样一个无效的代码点,您的异常被抛出。但是在该点之前可能有数百或数千个字节对是有效的 UTF-16,如果不是清晰的文本。

关于UnicodeDecodeError : unexpected end of data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com