本文目录导读:

我来分享几个Python提取PDF文字的常用案例。
使用PyMuPDF (推荐)
import fitz # PyMuPDF
def extract_text_pymupdf(pdf_path):
"""使用PyMuPDF提取PDF文字"""
doc = fitz.open(pdf_path)
text = ""
for page_num in range(len(doc)):
page = doc[page_num]
text += page.get_text()
doc.close()
return text
# 使用示例
pdf_text = extract_text_pymupdf("example.pdf")
print(pdf_text)
使用pdfplumber (适合表格提取)
import pdfplumber
def extract_text_pdfplumber(pdf_path):
"""使用pdfplumber提取PDF文字"""
with pdfplumber.open(pdf_path) as pdf:
text = ""
for page in pdf.pages:
text += page.extract_text() + "\n"
return text
# 使用示例
pdf_text = extract_text_pdfplumber("example.pdf")
print(pdf_text)
使用PyPDF2 (基础功能)
import PyPDF2
def extract_text_pypdf2(pdf_path):
"""使用PyPDF2提取PDF文字"""
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
text = ""
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
text += page.extract_text()
return text
# 使用示例
pdf_text = extract_text_pypdf2("example.pdf")
print(pdf_text)
高级案例:带格式提取
import fitz
import pandas as pd
def extract_text_with_format(pdf_path):
"""提取文字并保持基本格式"""
doc = fitz.open(pdf_path)
results = []
for page_num in range(len(doc)):
page = doc[page_num]
# 获取文本块及其位置
blocks = page.get_text("blocks")
for block in blocks:
# block格式: (x0, y0, x1, y1, text, block_no, block_type)
x0, y0, x1, y1, text, block_no, block_type = block
results.append({
'page': page_num + 1,
'text': text.strip(),
'position': (x0, y0, x1, y1),
'type': 'text' if block_type == 0 else 'image'
})
doc.close()
return pd.DataFrame(results)
# 使用示例
df = extract_text_with_format("example.pdf")
print(df[df['type'] == 'text'][['page', 'text']])
批量处理多个PDF
import os
from pathlib import Path
import fitz
def batch_extract_pdf_text(input_dir, output_dir):
"""批量提取PDF文字"""
# 创建输出目录
Path(output_dir).mkdir(parents=True, exist_ok=True)
pdf_files = list(Path(input_dir).glob("*.pdf"))
for pdf_path in pdf_files:
try:
# 提取文字
doc = fitz.open(str(pdf_path))
text = ""
for page in doc:
text += page.get_text()
doc.close()
# 保存为txt文件
output_path = Path(output_dir) / f"{pdf_path.stem}.txt"
with open(output_path, 'w', encoding='utf-8') as f:
f.write(text)
print(f"✓ 已处理: {pdf_path.name}")
except Exception as e:
print(f"✗ 处理失败 {pdf_path.name}: {str(e)}")
# 使用示例
batch_extract_pdf_text("./pdf_files", "./output")
提取特定页面的文字
import fitz
def extract_specific_pages(pdf_path, pages):
"""提取指定页面的文字"""
doc = fitz.open(pdf_path)
text = ""
for page_num in pages:
if 0 <= page_num < len(doc):
page = doc[page_num]
text += f"--- 第{page_num + 1}页 ---\n"
text += page.get_text() + "\n\n"
doc.close()
return text
# 使用示例:提取第1、3、5页
text = extract_specific_pages("example.pdf", [0, 2, 4])
print(text)
安装依赖
# 推荐安装 pip install PyMuPDF pdfplumber PyPDF2 pandas
比较各库特点
| 库 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| PyMuPDF | 速度快,功能全面,支持中文 | 安装稍大 | 通用场景 |
| pdfplumber | 表格提取好,精确度高 | 速度较慢 | 表格提取 |
| PyPDF2 | 轻量,简单 | 支持格式有限 | 简单提取 |
推荐优先使用PyMuPDF,它在速度和功能上平衡最好,特别适合中文PDF的提取。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播