【问题标题】:Python 3 UnicodeDecodeError - How do I debug UnicodeDecodeError?Python 3 UnicodeDecodeError - 如何调试 UnicodeDecodeError?
【发布时间】:2018-02-21 03:58:39
【问题描述】:

我有一个文本文件,出版商(美国证券交易委员会)声称它是用 UTF-8 编码的(https://www.sec.gov/files/aqfs.pdf,第 4 节)。我正在使用以下代码处理这些行:

def tags(filename):
    """Yield Tag instances from tag.txt."""
    with codecs.open(filename, 'r', encoding='utf-8', errors='strict') as f:
        fields = f.readline().strip().split('\t')
        for line in f.readlines():
            yield process_tag_record(fields, line)

我收到以下错误:

Traceback (most recent call last):
  File "/home/randm/Projects/finance/secxbrl.py", line 151, in <module>
    main()
  File "/home/randm/Projects/finance/secxbrl.py", line 143, in main
    all_tags = list(tags("tag.txt"))
  File "/home/randm/Projects/finance/secxbrl.py", line 109, in tags
    content = f.read()
  File "/home/randm/Libraries/anaconda3/lib/python3.6/codecs.py", line 698, in read
    return self.reader.read(size)
  File "/home/randm/Libraries/anaconda3/lib/python3.6/codecs.py", line 501, in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xad in position 3583587: invalid start byte

鉴于我可能无法返回 SEC 并告诉他们他们的文件似乎不是以 UTF-8 编码的,我应该如何调试并捕获此错误?

我尝试了什么

我对文件进行了十六进制转储,发现有问题的文字是“非现金投资的补充披露”。如果我将违规字节解码为十六进制代码点(即“U+00AD”),则在上下文中是有意义的,因为它是软连字符。但以下似乎不起作用:

Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> b"\x41".decode("utf-8")
'A'
>>> b"\xad".decode("utf-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec cant decode byte 0xad in position 0: invalid start byte
>>> b"\xc2ad".decode("utf-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec cant decode byte 0xc2 in position 0: invalid continuation byte

我用过errors='replace',似乎通过了。但我想了解如果我尝试将其插入数据库会发生什么。

十六进制转储:

0036ae40  31 09 09 09 09 53 55 50  50 4c 45 4d 45 4e 54 41  |1....SUPPLEMENTA|
0036ae50  4c 20 44 49 53 43 4c 4f  53 55 52 45 20 4f 46 20  |L DISCLOSURE OF |
0036ae60  4e 4f 4e ad 43 41 53 48  20 49 4e 56 45 53 54 49  |NON.CASH INVESTI|
0036ae70  4e 47 20 41 4e 44 20 46  49 4e 41 4e 43 49 4e 47  |NG AND FINANCING|
0036ae80  20 41 43 54 49 56 49 54  49 45 53 3a 09 0a 50 72  | ACTIVITIES:..Pr|

【问题讨论】:

  • 在 Python 3.6 中,不要使用 codecs.open()。标准的open()函数可以更好更快地处理编码数据。
  • 实际的 hexdump 显示了什么? 十六进制,不是ASCII加替换字符。 U+00AD 字节将被编码为两个字节,0xC2 0xAD,因此您缺少 0xC2 字节。
  • 你是如何获取数据文件的?如果那里缺少一个字节,则可能还有其他数据损坏。
  • 接下来,我也不会使用readline()readlines() 电话;使用fields = next(f).strip().split('\t')for line in f:。这样可以避免在处理每一行之前立即将整个文件读入内存。
  • @HåkenLid:除了没有已知的编码可以产生 SEC 产生的输出。他们生成了无效的编解码器。

标签: python python-3.x unicode utf-8 character-encoding


【解决方案1】:

您的数据文件已损坏。如果该字符确实是 U+00AD SOFT HYPHEN,那么您缺少一个 0xC2 字节:

>>> '\u00ad'.encode('utf8')
b'\xc2\xad'

在以 0xAD 结尾的所有可能的 UTF-8 编码中,软连字符确实最有意义。但是,这表明 可能 缺少其他字节的数据集。你只是碰巧击中了一个重要的。

我将返回此数据集的源并验证文件在下载时没有损坏。否则,使用error='replace' 是一种可行的解决方法,前提是没有缺少分隔符(制表符、换行符等)。

另一种可能是SEC确实对文件使用了不同编码;例如在 Windows Codepage 1252 和 Latin-1 中,0xAD 是软连字符的正确编码。事实上,当我下载same dataset directly (warning, large ZIP file linked) 并打开tags.txt 时,我无法将数据解码为UTF-8:

>>> open('/tmp/2017q1/tag.txt', encoding='utf8').read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xad in position 3583587: invalid start byte
>>> from pprint import pprint
>>> f = open('/tmp/2017q1/tag.txt', 'rb')
>>> f.seek(3583550)
3583550
>>> pprint(f.read(100))
(b'1\t1\t\t\t\tSUPPLEMENTAL DISCLOSURE OF NON\xadCASH INVESTING AND FINANCING A'
 b'CTIVITIES:\t\nProceedsFromSaleOfIn')

文件中有两个这样的非ASCII字符:

>>> f.seek(0)
0
>>> pprint([l for l in f if any(b > 127 for b in l)])
[b'SupplementalDisclosureOfNoncashInvestingAndFinancingActivitiesAbstract\t0'
 b'001654954-17-000551\t1\t1\t\t\t\tSUPPLEMENTAL DISCLOSURE OF NON\xadCASH I'
 b'NVESTING AND FINANCING ACTIVITIES:\t\n',
 b'HotelKranichhheMember\t0001558370-17-001446\t1\t0\tmember\tD\t\tHotel Krani'
 b'chhhe [Member]\tRepresents information pertaining to Hotel Kranichh\xf6h'
 b'e.\n']

Hotel Kranichh\xf6he 解码为 Latin-1 是 Hotel Kranichhöhe

文件中还有几个0xC1 / 0xD1对:

>>> f.seek(0)
0
>>> quotes = [l for l in f if any(b in {0x1C, 0x1D} for b in l)]
>>> quotes[0].split(b'\t')[-1][50:130]
b'Temporary Payroll Tax Cut Continuation Act of 2011 (\x1cTCCA\x1d) recognized during th'
>>> quotes[1].split(b'\t')[-1][50:130]
b'ributory defined benefit pension plan (the \x1cAetna Pension Plan\x1d) to allow certai'

我打赌那些真的是U+201C LEFT DOUBLE QUOTATION MARKU+201D RIGHT DOUBLE QUOTATION MARK 字符;注意1C1D 部分。感觉就像他们的编码器采用了 UTF-16 并去掉了所有高字节,而不是正确地编码为 UTF-8!

没有与 Python 一起提供的编解码器可以将 '\u201C\u201D' 编码为 b'\x1C\x1D',这使得 SEC 更有可能在某个地方搞砸了他们的编码过程。事实上,还有 0x13 和 0x14 字符可能是 enem 破折号(U+2013U+2014),以及几乎可以肯定的 0x19 字节单引号 (U+2019)。完成图片所缺少的只是一个 0x18 字节来表示U+2018

如果我们假设编码被破坏,我们可以尝试修复。以下代码将读取文件并修复引号问题,假设其余数据不使用除引号之外的 Latin-1 字符:

_map = {
    # dashes
    0x13: '\u2013', 0x14: '\u2014',
    # single quotes
    0x18: '\u2018', 0x19: '\u2019',
    # double quotes
    0x1c: '\u201c', 0x1d: '\u201d',
}
def repair(line, _map=_map):
    """Repair mis-encoded SEC data. Assumes line was decoded as Latin-1"""
    return line.translate(_map)

然后将其应用于您阅读的行:

with open(filename, 'r', encoding='latin-1') as f:
    repaired = map(repair, f)
    fields = next(repaired).strip().split('\t')
    for line in repaired:
        yield process_tag_record(fields, line)

另外,解决您发布的代码,您正在使 Python 比它需要的更努力地工作。不要使用codecs.open();这是具有已知问题并且比新的 Python 3 I/O 层慢的遗留代码。只需使用open()。不要使用f.readlines();您无需将整个文件读入此处的列表。直接遍历文件即可:

def tags(filename):
    """Yield Tag instances from tag.txt."""
    with open(filename, 'r', encoding='utf-8', errors='strict') as f:
        fields = next(f).strip().split('\t')
        for line in f:
            yield process_tag_record(fields, line)

如果process_tag_record 也在选项卡上拆分,请使用csv.reader() 对象并避免手动拆分每一行:

import csv

def tags(filename):
    """Yield Tag instances from tag.txt."""
    with open(filename, 'r', encoding='utf-8', errors='strict') as f:
        reader = csv.reader(f, delimiter='\t')
        fields = next(reader)
        for row in reader:
            yield process_tag_record(fields, row)

如果process_tag_recordfields 列表与row 中的值组合成一个字典,只需使用csv.DictReader() 代替:

def tags(filename):
    """Yield Tag instances from tag.txt."""
    with open(filename, 'r', encoding='utf-8', errors='strict') as f:
        reader = csv.DictReader(f, delimiter='\t')
        # first row is used as keys for the dictionary, no need to read fields manually.
        yield from reader

【讨论】:

  • 我必须在 process_tag_record 中做更多的工作,而不仅仅是压缩和返回(例如将数据转换为 Python 数据类型,创建 SQLAlchemy 实例),但是是的,如果它只是这样会更好一个拉链然后返回。
  • 根据您的“去掉高字节的 UTF-16”,这正是它的样子。也有遵循相同模式的单引号和 em 和破折号。
  • @MarkTolonen:确实;我发现了 5 个不同的“异常”,即 0x00 和 0x1F 之间的字节(不包括 0x09 和 0x0A,或换行符和制表符)。
  • @tripleee:有趣。我一般使用 fileformat.info charactersetunicode 页面来交叉引用字符;他们有 comprehensive, per-codepoint listings of character setsWindows codepages 来检查。对于其他损坏的编码问题,ftfy project 非常宝贵。
  • @tripleee:再次感谢该页面,was helpful in finding a weird codec once more
猜你喜欢
  • 2011-10-14
  • 2017-05-03
  • 2017-07-26
  • 1970-01-01
  • 2014-07-18
  • 2016-02-20
相关资源
最近更新 更多