PDFPlumber解析PDF文本报错:AssertionError: (‘Unhandled’, 6)

文章目录

1、问题描述

今天在使用PDFPlumber模块提取PDF文本时extract_text()方法报错,报错内容如下:

python 复制代码
Traceback (most recent call last):
  ......
  File "F:\Python\...\site-packages\pdfminer\pdffont.py", line 1091, in __init__
    self.unicode_map = ttf.create_unicode_map()
  File "F:\Python\...\site-packages\pdfminer\pdffont.py", line 826, in create_unicode_map
    assert False, str(("Unhandled", fmttype))
AssertionError: ('Unhandled', 6)

报错代码如下:

python 复制代码
import pdfplumber

with pdfplumber.open(rf'F:\...\file.pdf') as pdf:
    for page in pdf.pages:
        print(page.extract_text())

2、问题原因

经查找原因,最终确定可能是PDF文件本身的原因,具体可见这篇文章:https://github.com/jsvine/pdfplumber/discussions/994?sort=new

ChatGPT则认这种错误是因为库内部遇到了某种它无法处理的情况,ChatGPT给出的解决方案如下:

1) 更新PDFPlumber

python 复制代码
pip install --upgrade pdfplumber

2) 检查PDF文件

确认PDF文件没有损坏,并且是文本格式的PDF而不是扫描的图像

3) 使用其他方法

可以尝试使用extract_words()extract_tables()等其他方法,这取决于你需要提取的内容类型

4) 捕获异常

添加异常处理,这样即使遇到错误也不会导致程序崩溃

python 复制代码
try:
    text = page.extract_text()
except AssertionError as e:
    print(e)
    text = None

5) 尝试其他库

可以考虑使用其他PDF处理库,如PyPDF2或PyMuPDF等

在尝试了ChatGPT的一些建议后,确定可能是PDF本身的原因,因此考虑使用其他库

3、问题解决

经过尝试,最终发现PyMuPDF库可以解析使用:

python 复制代码
import fitz

with fitz.open(rf'F:\...\file.pdf') as doc:
    for page in doc.pages():
        print(page.get_text())

看来是PDF本身的原因,我们的PDF可能已经损坏

相关推荐
忡黑梨3 分钟前
BUUCTF_reverse_[MRCTF2020]Transform
c语言·开发语言·数据结构·python·算法·网络安全
芝士爱知识a16 分钟前
2026年 AI 期权工具全维度测评与推荐榜单:AlphaGBM 领跑,量化交易新范式
大数据·人工智能·python·ai量化·alphagbm·ai期权工具·ai期权工具推荐
天远Date Lab16 分钟前
天远入职背调报告API对接实战:Python构建自动化背景调查中台
大数据·网络·python·自动化
一叶萩Charles17 分钟前
MCP 实战:国家统计局数据查询 Server 从开发到发布
javascript·人工智能·python·node.js
chushiyunen25 分钟前
python双下划线魔术方法(特殊方法)(双下划线方法)
python
米码收割机28 分钟前
【AI】OpenClaw问题排查
开发语言·数据库·c++·python
所谓伊人,在水一方33329 分钟前
【Python数据科学实战之路】第10章 | 机器学习基础:从理论到实践的完整入门
开发语言·人工智能·python·机器学习·matplotlib
王夏奇29 分钟前
Python-对excel文件操作-pandas库
python·excel·pandas
无风听海30 分钟前
Python之TypeVar深入解析
开发语言·python·typevar
独断万古他化31 分钟前
Python 接口测试之 requests 库核心用法
python·pytest·接口测试·requests