目錄 專欄導讀 概述 主要工具庫介紹 1. tabula-py 2. camelot-py 3. pdfplumber 4. PyMuPDF (fitz) 環境準備 安裝依賴 Java環境配置(tabula-py需要) 方法一:使用tabula-py提取表格 方法二:使用camelot-py提取表格 方法三:使用pdfplumber提取表格 批量處理多個PDF文件 數據后處理和清洗 完整的批量處理腳本 使用示例 常見問題和解決方案 1. Java環境問題 2. 表格識別不準確 3. 內存不足 4. 中文編碼問題 性能優化建議 總結 結尾
專欄導讀
?? 歡迎來到Python辦公自動化專欄—Python處理辦公問題,解放您的雙手 ?????? 博客主頁:請點擊——> 一晌小貪歡的博客主頁求關注 ?? 該系列文章專欄:請點擊——>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 Pathdef 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) . stemfor 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) . stemfor 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 pddef extract_tables_with_camelot ( pdf_path, output_dir) : """使用camelot-py提取PDF表格"&