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可能已经损坏

相关推荐
0思必得026 分钟前
[Web自动化] CSS基础概念和介绍
前端·css·python·自动化·html·web自动化
计算机徐师兄28 分钟前
Python基于Django的MOOC线上课程推荐数据分析与可视化系统(附源码,文档说明)
python·数据分析·django·慕课线上课程推荐·慕课线上课程推荐可视化系统·pytho线上课程推荐可视化·线上课程推荐数据分析可视化系统
free-elcmacom31 分钟前
Python实战项目<2>使用Graphviz绘制流程框图
开发语言·python·graphviz
ljuncong38 分钟前
python的装饰器怎么使用
开发语言·python
该用户已不存在1 小时前
没有这7款工具,难怪你的Python这么慢
后端·python
serve the people1 小时前
tensorflow 零基础吃透:RaggedTensor 的不规则形状与广播机制 2
人工智能·python·tensorflow
Hello.Reader1 小时前
Flink ML 基本概念Table API、Stage、Pipeline 与 Graph
大数据·python·flink
chen_note1 小时前
Python面向对象、并发编程、网络编程
开发语言·python·网络编程·面向对象·并发编程
信看1 小时前
树莓派CAN(FD) 测试&&RS232 RS485 CAN Board 测试
开发语言·python
brent4231 小时前
DAY24推断聚类后簇的类型
python