【问题标题】:'utf-8' codec can't decode byte 0xe2 : invalid continuation byte error“utf-8”编解码器无法解码字节 0xe2:无效的继续字节错误
【发布时间】:2019-06-05 03:05:29
【问题描述】:

我正在尝试从文件夹中读取所有 PDF 文件以使用正则表达式查找数字。经检查,PDF 的字符集为“UTF-8”。

抛出此错误:

'utf-8' 编解码器无法解码位置 10 中的字节 0xe2:无效 继续字节

尝试以二进制模式读取, 尝试了 Latin-1 编码,但它显示了所有特殊字符,因此搜索中没有显示任何内容。

import os
import re
import pandas as pd
download_file_path = "C:\\Users\\...\\..\\"
for file_name in os.listdir(download_file_path):
    try:
        with open(download_file_path + file_name, 'r',encoding="UTF-8") as f:
          s = f.read()
          re_api = re.compile("API No\.\:\n(.*)")
          api = re_api.search(s).group(1).split('"')[0].strip()
          print(api)
    except Exception as e:
        print(e)

希望从 PDF 文件中找到 API 编号

【问题讨论】:

  • 试试encoding="ISO-8859-1"
  • 'NoneType' 对象没有属性 'group',我尝试时收到此错误
  • “经检查,PDF 的字符集是 'UTF-8'。” - 不,pdf 是二进制格式,通常包含大量压缩数据。甚至其中未压缩的字符串数据也可能以混合编码出现,几乎没有 utf-8。

标签: python pdf utf-8 decode


【解决方案1】:

PDF 文件存储为字节。 因此,要读取或写入 PDF 文件,您需要使用 rbwb

with open(file, 'rb') as fopen:
    q = fopen.read()
    print(q.decode())

'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte 可能是因为your editor 或 PDF 不是 utf 编码的(通常)。

因此使用,

with open(file, 'rb') as fopen:
        q = fopen.read()
        print(q.decode('latin-1')) #or any encoding which is suitable here.

如果您的editor console 不兼容,那么您也将看不到任何输出。

一个注意:你不能在使用rb时使用encoding参数,所以你必须在读取文件后解码。

【讨论】:

    【解决方案2】:

    当您使用open(..., 'r', encoding='utf-8') 打开文件时,您基本上可以保证这是一个不包含非 UTF-8 字节的文本文件。但当然,此保证不适用于 PDF 文件 - 它是一种二进制格式,可能包含 UTF-8 中的字符串。但这不是你读它的方式。

    如果您可以访问读取 PDF 并提取文本字符串的库,您可以这样做

    # Dunno if such a library exists, but bear with ...
    instance = myFantasyPDFlibrary('file.pdf')
    for text_snippet in instance.enumerate_texts_in_PDF():
        if 'API No.:\n' in text_snippet:
            api = text_snippet.split('API No.:\n')[1].split('\n')[0].split('"')[0].strip()
    

    更现实,但以更普通的方式,您可以将 PDF 文件作为二进制文件读取,然后查找编码文本。

    with open('file.pdf', 'rb') as pdf:
        pdfbytes = pdf.read()
    if b'API No.:\n' in pdfbytes:
        api_text = pdfbytes.split(b'API No.:\n')[1].split(b'\n')[0].decode('utf-8')
        api = api_text.split('"')[0].strip()
    

    一种粗略的解决方法是在编码方面对 Python 撒谎,并声称它实际上是 Latin-1。这种特殊的编码具有吸引人的特性,即每个字节都精确地映射到其自己的 Unicode 代码点,因此您可以将二进制数据作为文本读取并摆脱它。但是,当然,任何实际的 UTF-8 都将转换为 mojibake(例如,"hëlló" 将呈现为 "hëlló")。您可以提取实际的 UTF-8 文本,方法是将文本转换回字节,然后使用正确的编码 (latintext.encode('latin-1').decode('utf-8')) 对其进行解码。

    【讨论】:

    • 关于 Latin-1 的重要提示
    【解决方案3】:

    只需切换到不同的编解码器包:encoding = 'unicode_escape'

    【讨论】:

      【解决方案4】:

      问题可能是由于您的计算机名称, 我在 Python Django 框架中遇到了这个错误

      解决方案是“您的计算机名称不得包含特殊字符”,请检查并更改您的计算机名称...Changing computer name image

      【讨论】:

        猜你喜欢
        • 2014-12-24
        • 2021-03-12
        • 1970-01-01
        • 1970-01-01
        • 2018-01-11
        • 2020-11-02
        • 2021-01-02
        • 2021-04-27
        • 1970-01-01
        相关资源
        最近更新 更多