python - 'utf- 8' codec can' t 解码字节 0xe2 : invalid continuation byte error

标签 python pdf utf-8 decode

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

抛出这个错误:

'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte



尝试以二进制模式阅读,
尝试了 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 编号

最佳答案

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不兼容,那么您也将看不到任何输出。

A 注意 : 你不能使用 encoding使用 rb 时的参数所以你必须在阅读文件后解码。

关于python - 'utf- 8' codec can' t 解码字节 0xe2 : invalid continuation byte error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453782/

相关文章:

php - UTF-8贯穿始终

python - 统一码编码错误 : 'latin-1' codec can't encode character '\u2013' in position 637: ordinal not in range(256)

python - 更改静态类变量

python - ImportError : libgeos-3. 6.2.so:无法打开共享对象文件:没有这样的文件或目录

r - 将图像(png 文件)添加到使用 R 创建的 pdf 文件的标题中

java - 如何更改 iText 中的线条粗细?

ios - 将整个 UITableView 存储在 PDF 文件中

java - 如何在字符串中插入≠符号

python - 如何在 Pandas 的非时间索引上按值区间进行滑动窗口?

c++ - Boost.Python 自定义异常类