专栏导读
🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏
❤️ 欢迎各位佬关注! ❤️
概述
在日常工作中,我们经常需要从PDF文件中提取表格数据进行分析。手动复制粘贴不仅效率低下,还容易出错。本文将介绍如何使用Python自动化批量提取PDF中的表格数据,并将其转换为可处理的格式。
主要工具库介绍
1. tabula-py
- 优势:专门用于PDF表格提取,功能强大
- 特点:基于Java的tabula库,支持复杂表格结构
- 适用场景:结构化表格,边框清晰的PDF
2. camelot-py
- 优势:高精度表格提取,支持表格质量评估
- 特点:提供多种提取策略,可视化调试
- 适用场景:高质量PDF文档,需要精确提取
3. pdfplumber
- 优势:轻量级,易于使用
- 特点:可以提取文本、表格和图像信息
- 适用场景:简单表格,文本密集型PDF
4. PyMuPDF (fitz)
- 优势:功能全面,性能优秀
- 特点:支持多种PDF操作,包括表格提取
- 适用场景:复杂PDF处理需求
环境准备
安装依赖
pip install tabula-py
pip install camelot-py[cv]
pip install pdfplumber
pip install PyMuPDF
pip install pandas
pip install openpyxl xlsxwriter
Java环境配置(tabula-py需要)
java -version
方法一:使用tabula-py提取表格
基础用法
import tabula
import pandas as pd
import os
from pathlib import Path
def extract_tables_with_tabula(pdf_path, output_dir):
"""
使用tabula-py提取PDF中的表格
Args:
pdf_path: PDF文件路径
output_dir: 输出目录
"""
try:
tables = tabula.read_pdf(pdf_path, pages='all', multiple_tables=True)
pdf_name = Path(pdf_path).stem
for i, table in enumerate(tables):
if not table.empty:
output_file = os.path.join(output_dir, f"{
pdf_name}_table_{
i+1}.xlsx")
table.to_excel(output_file, index=False)
print(f"表格 {
i+1} 已保存到: {
output_file}")
return len(tables)
except Exception as e:
print(f"处理文件 {
pdf_path} 时出错: {
str(e)}")
return 0
pdf_file = "example.pdf"
output_directory = "extracted_tables"
os.makedirs(output_directory, exist_ok=True)
table_count = extract_tables_with_tabula(pdf_file, output_directory)
print(f"共提取了 {
table_count} 个表格")
高级配置
def advanced_tabula_extraction(pdf_path, output_dir):
"""
高级tabula提取配置
"""
try:
tables = tabula.read_pdf(
pdf_path,
pages='all',
multiple_tables=True,
lattice=True,
stream=False,
guess=True,
pandas_options={
'header': 0}
)
pdf_name = Path(pdf_path).stem
for i, table in enumerate(tables):
if not table.empty:
table = table.dropna(how='all')
table = table.dropna(axis=1, how='all')
base_name = f"{
pdf_name}_table_{
i+1}"
excel_file = os.path.join(output_dir, f"{
base_name}.xlsx")
table.to_excel(excel_file, index=False)
csv_file = os.path.join(output_dir, f"{
base_name}.csv")
table.to_csv(csv_file, index=False, encoding='utf-8-sig')
print(f"表格 {
i+1} 已保存: {
base_name}")
return len(tables)
except Exception as e:
print(f"处理失败: {
str(e)}")
return 0
方法二:使用camelot-py提取表格
import camelot
import pandas as pd
def extract_tables_with_camelot(pdf_path, output_dir):
"""
使用camelot-py提取PDF表格
"&