使用pdfplumber提取pdf中的文字

一、安装 pdfplumber

pdfplumber 是一个 Python 库,必须通过 pip 安装才能在 Python 代码中进行使用。使用以下命令在 Python 中安装 pdfplumber。

python 复制代码
pip install pdfplumber

二、用 pdfplumber 打开 PDF 文档

在 Python 中使用 pdfplumber 打开 PDF 文档的方法非常简单。只需要调用 pdfplumber 的 open 方法并传递 PDF 文件的路径。

python 复制代码
import pdfplumber
with pdfplumber.open("example.pdf") as pdf:
  # do something with pdf

三、提取文本

使用 pdfplumber 可以很容易地提取文档中的文本内容。对于一个页面,你可以使用 extract_text() 方法来提取页面上的文本。

python 复制代码
with pdfplumber.open("example.pdf") as pdf:
  for i, page in enumerate(pdf.pages):
    text = page.extract_text()
    print(f"This is the text on page {i}:")
    print(text)

使用 extract_text() 方法会返回一个字符串,其中包含页面中的所有文本。如果你只想提取页面的一部分文本,可以将提取的区域作为参数传递给 extract_text() 方法。

四、提取表格

如果 PDF 文档中包含表格,则可以使用 pdfplumber 将表格提取为 Pandas DataFrame 对象,并对其进行进一步处理。

首先,我们需要用 extract_tables() 方法来提取所有表格。

python 复制代码
with pdfplumber.open("example.pdf") as pdf:
  for i, page in enumerate(pdf.pages):
    tables = page.extract_tables()
    for table in tables:
      df = pd.DataFrame(table[1:], columns=table[0])
      print("This is a table on page ",i)
      print(df.head())

extract_tables() 方法将返回一个列表,其中包含每个表格的列表,每个表格都是一个嵌套列表。在将表格转换为 DataFrame 之前,请确保在第一行包含表头。

五、转换为图像

在某些情况下,你可能需要将 PDF 页面转换为图像格式,例如 PNG 或 JPEG。使用 pdfplumber 可以很容易地实现这一点。

首先,我们需要使用 Page 对象的 render() 方法将页面渲染为图像。

python 复制代码
with pdfplumber.open("example.pdf") as pdf:
  for i, page in enumerate(pdf.pages):
    im = page.to_image(resolution=150)
    im.save("page-{}.png".format(i), format="png")

render() 方法将返回一个 PageImage 对象,你可以使用该对象的 save() 方法将图像保存到文件。在 save() 方法中指定文件名和所需的图像格式。

相关推荐
曲幽7 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805112 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon13 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly13 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程14 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly16 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python