pdfplumber 是一个 Python 库,专门用于从 PDF 文件中提取文本和表格数据。相比其他 PDF 处理库,它提供了更精确的页面元素定位和更灵活的提取选项。
主要特点 #
- 精确的文本提取:保留原始布局和位置信息
- 表格提取功能:能识别复杂表格结构
- 可视化调试:可以绘制提取的文本和表格边界
- 页面分析:获取字符、线、矩形等底层PDF元素
基本用法 #
安装 #
pip install pdfplumber打开PDF文件 #
import pdfplumber
with pdfplumber.open("example.pdf") as pdf:
# 处理PDF内容
pass提取文本 #
# 提取单页文本
with pdfplumber.open("example.pdf") as pdf:
first_page = pdf.pages[0]
text = first_page.extract_text()
print(text)
# 提取所有页文本
with pdfplumber.open("example.pdf") as pdf:
all_text = ""
for page in pdf.pages:
all_text += page.extract_text()
print(all_text)提取表格 #
with pdfplumber.open("example.pdf") as pdf:
first_page = pdf.pages[0]
table = first_page.extract_table()
# 表格以二维列表形式返回
for row in table:
print(row)高级功能 #
表格提取设置 #
table_settings = {
"vertical_strategy": "text", # 或"lines", "explicit"
"horizontal_strategy": "text",
"intersection_y_tolerance": 10,
}
with pdfplumber.open("example.pdf") as pdf:
page = pdf.pages[0]
table = page.extract_table(table_settings)可视化调试 #
with pdfplumber.open("example.pdf") as pdf:
page = pdf.pages[0]
# 绘制文本边界
im = page.to_image()
im.debug_tablefinder().show()
# 绘制线条
im.reset().draw_lines(page.lines).show()获取字符级信息 #
with pdfplumber.open("example.pdf") as pdf:
page = pdf.pages[0]
for char in page.chars:
print(f"字符: {char['text']}, 位置: ({char['x0']}, {char['top']})")与其他库的比较 #
| 特性 | pdfplumber | PyPDF2 | pdfminer.six | camelot |
|---|---|---|---|---|
| 文本提取 | ✓ | ✓ | ✓ | ✓ |
| 表格提取 | ✓ | ✗ | ✗ | ✓ |
| 保留布局 | ✓ | ✗ | ✓ | ✓ |
| 可视化调试 | ✓ | ✗ | ✗ | ✓ |
| 性能 | 中等 | 快 | 慢 | 慢 |
实际应用示例 #
提取发票数据 #
with pdfplumber.open("invoice.pdf") as pdf:
first_page = pdf.pages[0]
# 查找"总计"后的金额
words = first_page.extract_words()
for i, word in enumerate(words):
if word["text"] == "总计":
total = words[i+1]["text"]
print(f"发票总计金额: {total}")
break批量处理多个PDF #
import os
import pandas as pd
results = []
for filename in os.listdir("pdfs"):
if filename.endswith(".pdf"):
with pdfplumber.open(f"pdfs/{filename}") as pdf:
first_page = pdf.pages[0]
text = first_page.extract_text()
results.append({"filename": filename, "content": text})
df = pd.DataFrame(results)
df.to_csv("pdf_contents.csv", index=False)性能优化技巧 #
- 限制处理页数:只处理需要的页面
- 使用缓存:对重复处理的PDF缓存结果
- 并行处理:对多个PDF使用多进程
- 调整提取策略:根据PDF特点选择合适的表格提取策略
常见问题解决 #
表格提取不准确:
- 尝试不同的提取策略
- 调整容差参数
- 先用可视化调试查看识别情况
文本顺序错乱:
- 使用
extract_text(x_tolerance=3, y_tolerance=3)调整容差 - 按字符位置手动排序
- 使用
内存不足:
- 逐页处理而不是加载整个PDF
- 使用
pdfplumber.open(..., laparams={"line_overlap": 0.7})减少分析强度
pdfplumber 是处理PDF文本和表格数据的强大工具,特别适合需要精确提取结构化数据的场景。