本文目录导读:

我来详细介绍几种从PDF提取文本的方法,包括使用Python脚本、命令行工具等。
Python脚本方案(最常用)
使用 PyMuPDF (fitz)
import fitz # PyMuPDF
def extract_text_from_pdf(pdf_path):
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_from_pdf("example.pdf")
print(pdf_text[:500]) # 打印前500个字符
使用 pdfplumber(适合处理表格)
import pdfplumber
def extract_text_with_pdfplumber(pdf_path):
text = ""
with pdfplumber.open(pdf_path) as pdf:
for page in pdf.pages:
text += page.extract_text() + "\n"
return text
# 使用示例
pdf_text = extract_text_with_pdfplumber("example.pdf")
使用 PyPDF2
import PyPDF2
def extract_text_pypdf2(pdf_path):
text = ""
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
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")
安装依赖
# 安装 PyMuPDF pip install PyMuPDF # 安装 pdfplumber pip install pdfplumber # 安装 PyPDF2 pip install PyPDF2
进阶功能脚本
带目录结构的PDF提取器
import os
import fitz
from pathlib import Path
class PDFTextExtractor:
def __init__(self, input_dir, output_dir):
self.input_dir = Path(input_dir)
self.output_dir = Path(output_dir)
self.output_dir.mkdir(exist_ok=True)
def extract_single_pdf(self, pdf_path):
"""提取单个PDF文件的文本"""
doc = fitz.open(pdf_path)
text_content = []
for page_num, page in enumerate(doc, 1):
text = page.get_text()
text_content.append(f"--- 第{page_num}页 ---\n{text}")
doc.close()
return "\n\n".join(text_content)
def save_to_file(self, pdf_name, text):
"""保存提取的文本到文件"""
txt_name = pdf_name.replace('.pdf', '.txt')
output_path = self.output_dir / txt_name
with open(output_path, 'w', encoding='utf-8') as f:
f.write(text)
print(f"已保存: {output_path}")
def process_all(self):
"""处理所有PDF文件"""
pdf_files = list(self.input_dir.glob("*.pdf"))
for pdf_file in pdf_files:
try:
text = self.extract_single_pdf(pdf_file)
self.save_to_file(pdf_file.name, text)
except Exception as e:
print(f"处理 {pdf_file.name} 时出错: {e}")
# 使用示例
extractor = PDFTextExtractor("input_pdfs", "output_texts")
extractor.process_all()
命令行工具方案
使用 pdftotext(Linux/Mac)
# 安装 sudo apt-get install poppler-utils # Ubuntu/Debian brew install poppler # macOS # 提取文本 pdftotext input.pdf output.txt # 保持布局 pdftotext -layout input.pdf output.txt # 只提取特定页面 pdftotext -f 1 -l 5 input.pdf pages_1-5.txt
使用 Pandoc
# 安装 Pandoc sudo apt-get install pandoc # Linux # 或从官网下载安装 # PDF转Markdown pandoc input.pdf -t markdown -o output.md # PDF转纯文本 pandoc input.pdf -t plain -o output.txt
处理扫描PDF(OCR方式)
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
def extract_text_from_scanned_pdf(pdf_path):
"""从扫描版PDF提取文本(需要OCR)"""
# 将PDF转换为图片
images = convert_from_path(pdf_path)
text = ""
for i, image in enumerate(images):
# 使用Tesseract进行OCR识别
page_text = pytesseract.image_to_string(image, lang='chi_sim+eng')
text += f"--- 第{i+1}页 ---\n{page_text}\n"
return text
# 安装依赖
# pip install pytesseract pdf2image Pillow
# 还需要安装Tesseract OCR引擎
批量处理脚本
#!/usr/bin/env python3
# batch_pdf_extract.py
import os
import sys
import argparse
from pathlib import Path
import fitz
def batch_extract(input_dir, output_dir, extension='.txt'):
"""批量提取PDF文本"""
input_path = Path(input_dir)
output_path = Path(output_dir)
output_path.mkdir(exist_ok=True)
pdf_files = list(input_path.glob("*.pdf"))
for pdf_file in pdf_files:
try:
doc = fitz.open(pdf_file)
text = ""
for page in doc:
text += page.get_text()
doc.close()
# 保存为文本文件
txt_file = output_path / f"{pdf_file.stem}{extension}"
with open(txt_file, 'w', encoding='utf-8') as f:
f.write(text)
print(f"✓ {pdf_file.name} -> {txt_file.name}")
except Exception as e:
print(f"✗ {pdf_file.name}: {e}")
def main():
parser = argparse.ArgumentParser(description='从PDF提取文本')
parser.add_argument('input_dir', help='PDF文件目录')
parser.add_argument('-o', '--output', default='extracted_texts',
help='输出目录(默认: extracted_texts)')
parser.add_argument('-e', '--extension', default='.txt',
help='输出文件扩展名(默认: .txt)')
args = parser.parse_args()
batch_extract(args.input_dir, args.output, args.extension)
if __name__ == "__main__":
main()
使用方式:
# 批量提取 python batch_pdf_extract.py ./pdfs -o ./texts # 指定输出格式 python batch_pdf_extract.py ./pdfs -o ./output -e .md
注意事项
- PDF类型:文本型PDF效果好,扫描型PDF需要OCR
- 编码问题:注意中文PDF的编码处理
- 复杂排版:表格、多栏排版可能提取顺序混乱
- 性能考虑:大批量PDF建议使用fitz或pdfplumber
选择哪种方法取决于你的具体需求:
- 简单提取:PyMuPDF (fitz) 速度快
- 保持格式:pdfplumber 或 pdftotext -layout
- 扫描PDF:需要结合OCR工具
- 批量处理:使用脚本自动化