Python使用Camelot從PDF中精準獲取表格數據
前言-為什么PDF表格數據提取如此重要
在數據分析與業(yè)務智能領域,PDF文檔中的表格數據是一座巨大的"金礦",卻因其封閉格式成為數據從業(yè)者的"噩夢"。從企業(yè)財報到政府統(tǒng)計數據,從科研論文到市場調研報告,關鍵信息常常被鎖在PDF表格中,無法直接用于分析。傳統(tǒng)方法如手動復制粘貼不僅效率低下,還容易引入錯誤;通用PDF解析工具在處理復雜表格時又常常力不從心。Camelot作為專門針對PDF表格提取設計的Python庫,憑借其精確的表格識別能力和靈活的配置選項,成為數據專業(yè)人員的得力助手。本文將全面介紹Camelot的使用技巧,從基礎安裝到高級應用,幫助您掌握PDF表格數據提取的專業(yè)技能。
1. Camelot基礎入門
1.1 安裝與環(huán)境配置
Camelot的安裝非常簡單,但需要注意一些依賴項:
# 基本安裝 pip install camelot-py[cv] # 如果需要PDF轉換功能 pip install ghostscript
對于完整功能,確保安裝以下依賴:
- Ghostscript:用于PDF文件處理
- OpenCV:用于圖像處理和表格檢測
- Tkinter:用于可視化功能(可選)
在Windows系統(tǒng)上,還需要單獨安裝Ghostscript,并將其添加到系統(tǒng)路徑中。
基本導入:
import camelot import pandas as pd import matplotlib.pyplot as plt import cv2
1.2 基本表格提取
def extract_basic_tables(pdf_path, pages='1'): """從PDF中提取基本表格""" # 使用stream模式提取表格 tables = camelot.read_pdf(pdf_path, pages=pages, flavor='stream') print(f"檢測到 {len(tables)} 個表格") # 表格基本信息 for i, table in enumerate(tables): print(f"\n表格 #{i+1}:") print(f"頁碼: {table.page}") print(f"表格區(qū)域: {table.area}") print(f"維度: {table.shape}") print(f"準確度分數: {table.accuracy}") print(f"空白率: {table.whitespace}") # 顯示表格前幾行 print("\n表格預覽:") print(table.df.head()) return tables # 使用示例 tables = extract_basic_tables("financial_report.pdf", pages='1-3')
1.3 提取方法比較Stream vs Lattice
def compare_extraction_methods(pdf_path, page='1'): """比較Stream和Lattice兩種提取方法""" # 使用Stream方法 stream_tables = camelot.read_pdf(pdf_path, pages=page, flavor='stream') # 使用Lattice方法 lattice_tables = camelot.read_pdf(pdf_path, pages=page, flavor='lattice') # 比較結果 print(f"Stream方法: 檢測到 {len(stream_tables)} 個表格") print(f"Lattice方法: 檢測到 {len(lattice_tables)} 個表格") # 如果檢測到表格,比較第一個表格 if len(stream_tables) > 0 and len(lattice_tables) > 0: # 獲取第一個表格 stream_table = stream_tables[0] lattice_table = lattice_tables[0] # 比較準確度和空白率 print("\n準確度和空白率比較:") print(f"Stream - 準確度: {stream_table.accuracy}, 空白率: {stream_table.whitespace}") print(f"Lattice - 準確度: {lattice_table.accuracy}, 空白率: {lattice_table.whitespace}") # 比較表格形狀 print("\n表格維度比較:") print(f"Stream: {stream_table.shape}") print(f"Lattice: {lattice_table.shape}") # 返回兩種方法的表格 return stream_tables, lattice_tables return None, None # 使用示例 stream_tables, lattice_tables = compare_extraction_methods("report_with_tables.pdf")
2. 高級表格提取技術
2.1 精確定位表格區(qū)域
def extract_table_with_area(pdf_path, page='1', table_area=None): """使用精確區(qū)域坐標提取表格""" if table_area is None: # 默認值覆蓋整個頁面 table_area = [0, 0, 100, 100] # [x1, y1, x2, y2] 以百分比表示 # 使用Stream方法提取指定區(qū)域的表格 tables = camelot.read_pdf( pdf_path, pages=page, flavor='stream', table_areas=[f"{table_area[0]},{table_area[1]},{table_area[2]},{table_area[3]}"] ) print(f"在指定區(qū)域檢測到 {len(tables)} 個表格") # 顯示第一個表格 if len(tables) > 0: print("\n表格預覽:") print(tables[0].df.head()) return tables # 使用示例 - 提取頁面中間大約位置的表格 tables = extract_table_with_area("financial_report.pdf", table_area=[10, 30, 90, 70])
2.2 處理復雜表格
def extract_complex_tables(pdf_path, page='1'): """處理復雜表格的高級配置""" # 使用Lattice方法處理有邊框的復雜表格 lattice_tables = camelot.read_pdf( pdf_path, pages=page, flavor='lattice', line_scale=40, # 調整線條檢測靈敏度 process_background=True, # 處理背景 line_margin=2 # 線條間隔容忍度 ) # 使用Stream方法處理無邊框的復雜表格 stream_tables = camelot.read_pdf( pdf_path, pages=page, flavor='stream', edge_tol=500, # 邊緣容忍度 row_tol=10, # 行容忍度 column_tol=10 # 列容忍度 ) print(f"Lattice方法: 檢測到 {len(lattice_tables)} 個表格") print(f"Stream方法: 檢測到 {len(stream_tables)} 個表格") # 選擇最佳結果 best_tables = lattice_tables if lattice_tables[0].accuracy > stream_tables[0].accuracy else stream_tables return best_tables # 使用示例 complex_tables = extract_complex_tables("complex_financial_report.pdf")
2.3 表格可視化與調試
def visualize_table_extraction(pdf_path, page='1'): """可視化表格提取過程,幫助調試和優(yōu)化""" # 提取表格 tables = camelot.read_pdf(pdf_path, pages=page) # 檢查是否成功提取表格 if len(tables) == 0: print("未檢測到表格") return # 獲取第一個表格 table = tables[0] # 顯示表格 print(f"表格形狀: {table.shape}") print(f"準確度: {table.accuracy}") # 繪制表格結構 plot = table.plot(kind='grid') plt.title(f"表格網格結構 - 準確度: {table.accuracy}") plt.tight_layout() plt.savefig('table_grid.png') plt.close() # 繪制表格單元格 plot = table.plot(kind='contour') plt.title(f"表格單元格結構 - 空白率: {table.whitespace}") plt.tight_layout() plt.savefig('table_contour.png') plt.close() # 繪制表格線條(僅適用于lattice方法) if table.flavor == 'lattice': plot = table.plot(kind='line') plt.title("表格線條檢測") plt.tight_layout() plt.savefig('table_lines.png') plt.close() print("可視化圖形已保存") return tables # 使用示例 visualized_tables = visualize_table_extraction("quarterly_report.pdf")
3. 表格數據處理與清洗
3.1 表格數據清洗
def clean_table_data(table): """清洗從PDF提取的表格數據""" # 獲取DataFrame df = table.df.copy() # 1. 替換空白單元格 df = df.replace('', pd.NA) # 2. 清理多余空格 for col in df.columns: if df[col].dtype == object: # 僅處理字符串列 df[col] = df[col].str.strip() if df[col].notna().any() else df[col] # 3. 處理合并單元格的問題(向下填充) df = df.fillna(method='ffill') # 4. 檢測并移除頁眉或頁腳(通常出現在第一行或最后一行) if df.shape[0] > 2: # 檢查第一行是否為頁眉 if df.iloc[0].astype(str).str.contains('Page|頁碼|日期').any(): df = df.iloc[1:] # 檢查最后一行是否為頁腳 if df.iloc[-1].astype(str).str.contains('總計|合計|Total').any(): df = df.iloc[:-1] # 5. 重置索引 df = df.reset_index(drop=True) # 6. 設置第一行為列名(可選) # df.columns = df.iloc[0] # df = df.iloc[1:].reset_index(drop=True) return df # 使用示例 tables = camelot.read_pdf("financial_data.pdf") if tables: cleaned_df = clean_table_data(tables[0]) print(cleaned_df.head())
3.2 多表格合并
def merge_tables(tables, merge_method='vertical'): """合并多個表格""" if not tables or len(tables) == 0: return None dfs = [table.df for table in tables] if merge_method == 'vertical': # 垂直合并(適用于跨頁表格) merged_df = pd.concat(dfs, ignore_index=True) elif merge_method == 'horizontal': # 水平合并(適用于分列表格) merged_df = pd.concat(dfs, axis=1) else: raise ValueError("合并方法必須是 'vertical' 或 'horizontal'") # 清洗合并后的數據 # 刪除完全相同的重復行(可能來自表格頁眉) merged_df = merged_df.drop_duplicates() return merged_df # 使用示例 - 合并跨頁表格 tables = camelot.read_pdf("multipage_report.pdf", pages='1-3') if tables: merged_table = merge_tables(tables, merge_method='vertical') print(f"合并后表格大小: {merged_table.shape}") print(merged_table.head())
3.3 表格數據類型轉換
def convert_table_datatypes(df): """將表格數據轉換為適當的數據類型""" # 創(chuàng)建DataFrame副本 df = df.copy() for col in df.columns: # 嘗試將列轉換為數值型 try: # 檢查列是否包含數字(帶有貨幣符號或千位分隔符) if df[col].str.contains(r'[$¥€£]|\d,\d').any(): # 移除貨幣符號和千位分隔符 df[col] = df[col].replace(r'[$¥€£,]', '', regex=True) # 嘗試轉換為數值型 df[col] = pd.to_numeric(df[col]) print(f"列 '{col}' 已轉換為數值型") except (ValueError, AttributeError): # 嘗試轉換為日期型 try: df[col] = pd.to_datetime(df[col]) print(f"列 '{col}' 已轉換為日期型") except (ValueError, AttributeError): # 保持為字符串型 pass return df # 使用示例 tables = camelot.read_pdf("sales_report.pdf") if tables: df = clean_table_data(tables[0]) typed_df = convert_table_datatypes(df) print(typed_df.dtypes)
4. 實際應用場景
4.1 提取財務報表數據
def extract_financial_statements(pdf_path, pages='all'): """從年度報告中提取財務報表""" # 提取所有表格 tables = camelot.read_pdf( pdf_path, pages=pages, flavor='stream', edge_tol=500, row_tol=10 ) print(f"共提取了 {len(tables)} 個表格") # 查找財務報表(通過關鍵詞) balance_sheet = None income_statement = None cash_flow = None for table in tables: df = table.df # 檢查表格是否包含特定關鍵詞 text = ' '.join([' '.join(row) for row in df.values.tolist()]) if any(term in text for term in ['資產負債表', 'Balance Sheet', '財務狀況表']): balance_sheet = clean_table_data(table) print("找到資產負債表") elif any(term in text for term in ['利潤表', 'Income Statement', '損益表']): income_statement = clean_table_data(table) print("找到利潤表") elif any(term in text for term in ['現金流量表', 'Cash Flow']): cash_flow = clean_table_data(table) print("找到現金流量表") return { 'balance_sheet': balance_sheet, 'income_statement': income_statement, 'cash_flow': cash_flow } # 使用示例 financial_data = extract_financial_statements("annual_report_2022.pdf", pages='10-30') for statement_name, df in financial_data.items(): if df is not None: print(f"\n{statement_name}:") print(df.head())
4.2 批量處理多個PDF
def batch_process_pdfs(pdf_folder, output_folder='extracted_tables'): """批量處理多個PDF文件,提取所有表格""" import os from pathlib import Path # 創(chuàng)建輸出文件夾 Path(output_folder).mkdir(exist_ok=True) # 獲取所有PDF文件 pdf_files = [f for f in os.listdir(pdf_folder) if f.lower().endswith('.pdf')] results = {} for pdf_file in pdf_files: pdf_path = os.path.join(pdf_folder, pdf_file) pdf_name = os.path.splitext(pdf_file)[0] print(f"\n處理: {pdf_file}") # 創(chuàng)建PDF專屬輸出文件夾 pdf_output_folder = os.path.join(output_folder, pdf_name) Path(pdf_output_folder).mkdir(exist_ok=True) try: # 提取表格 tables = camelot.read_pdf(pdf_path, pages='all') print(f"從 {pdf_file} 提取了 {len(tables)} 個表格") # 保存每個表格為CSV文件 for i, table in enumerate(tables): df = clean_table_data(table) output_path = os.path.join(pdf_output_folder, f"table_{i+1}.csv") df.to_csv(output_path, index=False, encoding='utf-8-sig') # 記錄結果 results[pdf_file] = { 'status': 'success', 'tables_count': len(tables), 'output_folder': pdf_output_folder } except Exception as e: print(f"處理 {pdf_file} 時出錯: {str(e)}") results[pdf_file] = { 'status': 'error', 'error_message': str(e) } # 匯總報告 success_count = sum(1 for result in results.values() if result['status'] == 'success') print(f"\n批處理完成。成功: {success_count}/{len(pdf_files)}") return results # 使用示例 batch_results = batch_process_pdfs("reports_folder", "extracted_data")
4.3 制作交互式數據儀表板
def create_dashboard_from_tables(tables, output_html='table_dashboard.html'): """從提取的表格創(chuàng)建簡單的交互式儀表板""" import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd # 確保我們有表格 if not tables or len(tables) == 0: print("沒有表格數據可用于創(chuàng)建儀表板") return # 為了簡單起見,使用第一個表格 df = clean_table_data(tables[0]) # 如果所有列都是字符串,嘗試將其中一些轉換為數值 df = convert_table_datatypes(df) # 創(chuàng)建儀表板 HTML with open(output_html, 'w', encoding='utf-8') as f: f.write("<html><head>") f.write("<title>PDF表格數據儀表板</title>") f.write("<style>body {font-family: Arial; margin: 20px;} .chart {margin: 20px 0; padding: 20px; border: 1px solid #ddd;}</style>") f.write("</head><body>") f.write("<h1>PDF表格數據儀表板</h1>") # 添加表格 f.write("<div class='chart'>") f.write("<h2>提取的表格數據</h2>") f.write(df.to_html(classes='dataframe', index=False)) f.write("</div>") # 如果有數值型列,創(chuàng)建圖表 numeric_cols = df.select_dtypes(include=['number']).columns if len(numeric_cols) > 0: # 選擇第一個數值列創(chuàng)建圖表 value_col = numeric_cols[0] # 尋找一個可能的類別列 category_col = None for col in df.columns: if col != value_col and df[col].dtype == object and df[col].nunique() < len(df) * 0.5: category_col = col break if category_col: # 創(chuàng)建條形圖 fig = px.bar(df, x=category_col, y=value_col, title=f"{category_col} vs {value_col}") f.write("<div class='chart'>") f.write(f"<h2>{category_col} vs {value_col}</h2>") f.write(fig.to_html(full_html=False)) f.write("</div>") # 創(chuàng)建餅圖 fig = px.pie(df, names=category_col, values=value_col, title=f"{value_col} by {category_col}") f.write("<div class='chart'>") f.write(f"<h2>{value_col} by {category_col} (餅圖)</h2>") f.write(fig.to_html(full_html=False)) f.write("</div>") f.write("</body></html>") print(f"儀表板已創(chuàng)建: {output_html}") return output_html # 使用示例 tables = camelot.read_pdf("sales_by_region.pdf") if tables: dashboard_path = create_dashboard_from_tables(tables)
5. 高級配置與優(yōu)化
5.1 優(yōu)化表格檢測參數
def optimize_table_detection(pdf_path, page='1'): """優(yōu)化表格檢測參數,嘗試不同設置并評估結果""" # 定義不同的參數組合 stream_configs = [ {'edge_tol': 50, 'row_tol': 5, 'column_tol': 5}, {'edge_tol': 100, 'row_tol': 10, 'column_tol': 10}, {'edge_tol': 500, 'row_tol': 15, 'column_tol': 15} ] lattice_configs = [ {'process_background': True, 'line_scale': 15}, {'process_background': True, 'line_scale': 40}, {'process_background': True, 'line_scale': 60, 'iterations': 1} ] results = [] # 測試Stream方法的不同配置 print("測試Stream方法...") for config in stream_configs: try: tables = camelot.read_pdf( pdf_path, pages=page, flavor='stream', **config ) # 評估結果 if len(tables) > 0: accuracy = tables[0].accuracy whitespace = tables[0].whitespace print(f"配置 {config}: 準確度={accuracy:.2f}, 空白率={whitespace:.2f}") results.append({ 'flavor': 'stream', 'config': config, 'tables_found': len(tables), 'accuracy': accuracy, 'whitespace': whitespace, 'tables': tables }) except Exception as e: print(f"配置 {config} 出錯: {str(e)}") # 測試Lattice方法的不同配置 print("\n測試Lattice方法...") for config in lattice_configs: try: tables = camelot.read_pdf( pdf_path, pages=page, flavor='lattice', **config ) # 評估結果 if len(tables) > 0: accuracy = tables[0].accuracy whitespace = tables[0].whitespace print(f"配置 {config}: 準確度={accuracy:.2f}, 空白率={whitespace:.2f}") results.append({ 'flavor': 'lattice', 'config': config, 'tables_found': len(tables), 'accuracy': accuracy, 'whitespace': whitespace, 'tables': tables }) except Exception as e: print(f"配置 {config} 出錯: {str(e)}") # 找出最佳配置 if results: # 按準確度排序 best_result = sorted(results, key=lambda x: x['accuracy'], reverse=True)[0] print(f"\n最佳配置: {best_result['flavor']} 方法, 參數: {best_result['config']}") print(f"準確度: {best_result['accuracy']:.2f}, 空白率: {best_result['whitespace']:.2f}") return best_result['tables'] return None # 使用示例 optimized_tables = optimize_table_detection("complex_report.pdf")
5.2 處理掃描PDF
def extract_tables_from_scanned_pdf(pdf_path, page='1'): """從掃描PDF中提取表格(需要預處理)""" import cv2 import numpy as np import tempfile from pdf2image import convert_from_path # 轉換PDF頁面為圖像 images = convert_from_path(pdf_path, first_page=int(page), last_page=int(page)) if not images: print("無法轉換PDF頁面為圖像") return None # 獲取第一個頁面圖像 image = np.array(images[0]) # 圖像預處理 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)[1] # 保存處理后的圖像 with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp: temp_image_path = tmp.name cv2.imwrite(temp_image_path, thresh) print(f"掃描頁面已預處理并保存為臨時圖像: {temp_image_path}") # 從圖像中提取表格 tables = camelot.read_pdf( pdf_path, pages=page, flavor='lattice', process_background=True, line_scale=150 ) print(f"從掃描PDF提取了 {len(tables)} 個表格") # 可選: 移除臨時文件 import os os.unlink(temp_image_path) return tables # 使用示例 scanned_tables = extract_tables_from_scanned_pdf("scanned_report.pdf")
5.3 處理合并單元格
def handle_merged_cells(table): """處理表格中的合并單元格""" # 獲取DataFrame df = table.df.copy() # 檢測并處理垂直合并的單元格 for col in df.columns: # 在連續(xù)的空單元格上向下填充值 mask = df[col].eq('') if mask.any(): prev_value = None fill_values = [] for idx, is_empty in enumerate(mask): if not is_empty: prev_value = df.at[idx, col] elif prev_value is not None: fill_values.append((idx, prev_value)) # 填充檢測到的合并單元格 for idx, value in fill_values: df.at[idx, col] = value # 檢測并處理水平合并的單元格 for idx, row in df.iterrows(): empty_cols = row.index[row == ''].tolist() if empty_cols and idx > 0: # 檢查這一行是否有空單元格后跟非空單元格 for i, col in enumerate(empty_cols): if i + 1 < len(row) and row.iloc[i + 1] != '': # 可能是水平合并,從左側單元格填充 left_col_idx = row.index.get_loc(col) - 1 if left_col_idx >= 0 and row.iloc[left_col_idx] != '': df.at[idx, col] = row.iloc[left_col_idx] return df # 使用示例 tables = camelot.read_pdf("report_with_merged_cells.pdf") if tables: cleaned_df = handle_merged_cells(tables[0]) print(cleaned_df.head())
6. 與其他工具集成
6.1 與pandas深度集成
def analyze_extracted_table(table): """使用pandas分析提取的表格數據""" # 清潔數據 df = clean_table_data(table) # 轉換數據類型 df = convert_table_datatypes(df) # 基本統(tǒng)計分析 print("\n==== 基本統(tǒng)計分析 ====") numeric_cols = df.select_dtypes(include=['number']).columns if len(numeric_cols) > 0: print(df[numeric_cols].describe()) # 檢查缺失值 print("\n==== 缺失值分析 ====") missing = df.isnull().sum() print(missing[missing > 0]) # 類別變量分析 print("\n==== 類別變量分析 ====") categorical_cols = df.select_dtypes(include=['object']).columns for col in categorical_cols[:3]: # 只顯示前三個類別列 value_counts = df[col].value_counts() print(f"\n{col}:") print(value_counts.head()) # 相關性分析 if len(numeric_cols) >= 2: print("\n==== 相關性分析 ====") correlation = df[numeric_cols].corr() print(correlation) return df # 使用示例 tables = camelot.read_pdf("sales_data.pdf") if tables: analyzed_df = analyze_extracted_table(tables[0])
6.2 與matplotlib和seaborn可視化
def visualize_table_data(table, output_prefix='table_viz'): """使用matplotlib和seaborn可視化表格數據""" import matplotlib.pyplot as plt import seaborn as sns # 設置樣式 sns.set(style="whitegrid") # 清潔并轉換數據 df = clean_table_data(table) df = convert_table_datatypes(df) # 獲取數值列 numeric_cols = df.select_dtypes(include=['number']).columns if len(numeric_cols) == 0: print("沒有數值列可供可視化") return # 1. 熱圖 - 相關性 if len(numeric_cols) >= 2: plt.figure(figsize=(10, 8)) corr = df[numeric_cols].corr() mask = np.triu(np.ones_like(corr, dtype=bool)) sns.heatmap(corr, mask=mask, annot=True, fmt=".2f", cmap='coolwarm', square=True, linewidths=.5) plt.title('相關性熱圖', fontsize=15) plt.tight_layout() plt.savefig(f'{output_prefix}_correlation.png') plt.close() # 2. 條形圖 - 數值分布 for col in numeric_cols[:3]: # 只處理前三個數值列 plt.figure(figsize=(12, 6)) sns.barplot(x=df.index, y=df[col]) plt.title(f'{col} 分布', fontsize=15) plt.xticks(rotation=45) plt.tight_layout() plt.savefig(f'{output_prefix}_{col}_barplot.png') plt.close() # 3. 箱線圖 - 查找異常值 plt.figure(figsize=(12, 6)) sns.boxplot(data=df[numeric_cols]) plt.title('數值列箱線圖', fontsize=15) plt.tight_layout() plt.savefig(f'{output_prefix}_boxplot.png') plt.close() # 4. 散點圖矩陣 - 變量關系 if len(numeric_cols) >= 2 and len(df) > 5: sns.pairplot(df[numeric_cols]) plt.suptitle('散點圖矩陣', y=1.02, fontsize=15) plt.tight_layout() plt.savefig(f'{output_prefix}_pairplot.png') plt.close() print(f"可視化圖表已保存,前綴: {output_prefix}") return df # 使用示例 tables = camelot.read_pdf("product_sales.pdf") if tables: df = visualize_table_data(tables[0], output_prefix='sales_viz')
6.3 與Excel集成
def export_tables_to_excel(tables, output_path='extracted_tables.xlsx'): """將提取的表格導出到Excel工作簿的不同工作表""" import pandas as pd # 檢查是否有表格 if not tables or len(tables) == 0: print("沒有表格可導出") return None # 創(chuàng)建Excel Writer對象 with pd.ExcelWriter(output_path, engine='xlsxwriter') as writer: workbook = writer.book # 創(chuàng)建表格樣式 header_format = workbook.add_format({ 'bold': True, 'text_wrap': True, 'valign': 'top', 'fg_color': '#D7E4BC', 'border': 1 }) cell_format = workbook.add_format({ 'border': 1 }) # 為每個表格創(chuàng)建工作表 for i, table in enumerate(tables): # 清潔數據 df = clean_table_data(table) # 寫入數據 sheet_name = f'Table_{i+1}' df.to_excel(writer, sheet_name=sheet_name, index=False) # 獲取工作表對象 worksheet = writer.sheets[sheet_name] # 設置列寬 for j, col in enumerate(df.columns): column_width = max( df[col].astype(str).map(len).max(), len(col) ) + 2 worksheet.set_column(j, j, column_width) # 設置表格格式 worksheet.add_table(0, 0, df.shape[0], df.shape[1] - 1, { 'columns': [{'header': col} for col in df.columns], 'style': 'Table Style Medium 9', 'header_row': True }) # 添加表格元數據 worksheet.write(df.shape[0] + 2, 0, f"頁碼: {table.page}") worksheet.write(df.shape[0] + 3, 0, f"表格區(qū)域: {table.area}") worksheet.write(df.shape[0] + 4, 0, f"準確度分數: {table.accuracy}") print(f"表格已導出至Excel: {output_path}") return output_path # 使用示例 tables = camelot.read_pdf("quarterly_report.pdf", pages='all') if tables: excel_path = export_tables_to_excel(tables, "quarterly_report_tables.xlsx")
7. 性能優(yōu)化與最佳實踐
7.1 處理大型PDF文檔
def process_large_pdf(pdf_path, batch_size=5, output_folder='large_pdf_tables'): """分批處理大型PDF文檔以節(jié)省內存""" import os from pathlib import Path # 創(chuàng)建輸出文件夾 Path(output_folder).mkdir(exist_ok=True) # 首先獲取PDF頁數 with pdfplumber.open(pdf_path) as pdf: total_pages = len(pdf.pages) print(f"PDF共有 {total_pages} 頁") # 分批處理頁面 all_tables_count = 0 for start_page in range(1, total_pages + 1, batch_size): end_page = min(start_page + batch_size - 1, total_pages) page_range = f"{start_page}-{end_page}" print(f"處理頁面范圍: {page_range}") try: # 提取當前批次的表格 tables = camelot.read_pdf( pdf_path, pages=page_range, flavor='stream', edge_tol=500 ) batch_tables_count = len(tables) all_tables_count += batch_tables_count print(f"從頁面 {page_range} 提取了 {batch_tables_count} 個表格") # 保存這一批次的表格 for i, table in enumerate(tables): table_index = all_tables_count - batch_tables_count + i + 1 df = clean_table_data(table) output_path = os.path.join(output_folder, f"table_{table_index}_p{table.page}.csv") df.to_csv(output_path, index=False, encoding='utf-8-sig') # 顯式釋放內存 tables = None import gc gc.collect() except Exception as e: print(f"處理頁面 {page_range} 時出錯: {str(e)}") print(f"處理完成,共提取了 {all_tables_count} 個表格,保存到 {output_folder}") return all_tables_count # 使用示例 table_count = process_large_pdf("very_large_report.pdf", batch_size=10)
7.2 Camelot性能調優(yōu)
def optimize_camelot_performance(pdf_path, page='1'): """調優(yōu)Camelot的性能參數""" import time import psutil import os def measure_performance(func, *args, **kwargs): """測量函數的執(zhí)行時間和內存使用情況""" process = psutil.Process(os.getpid()) mem_before = process.memory_info().rss / 1024 / 1024 # MB start_time = time.time() result = func(*args, **kwargs) end_time = time.time() mem_after = process.memory_info().rss / 1024 / 1024 # MB execution_time = end_time - start_time memory_used = mem_after - mem_before return result, execution_time, memory_used # 測試不同的參數組合 configs = [ { 'name': '默認配置', 'params': {} }, { 'name': '啟用后臺處理', 'params': {'process_background': True} }, { 'name': '禁用線條檢測', 'params': {'line_scale': 0} }, { 'name': '提高線條檢測靈敏度', 'params': {'line_scale': 80} } ] results = [] for config in configs: print(f"\n測試配置: {config['name']}") # 測試Lattice方法 try: lattice_func = lambda: camelot.read_pdf( pdf_path, pages=page, flavor='lattice', **config['params'] ) lattice_tables, lattice_time, lattice_mem = measure_performance(lattice_func) results.append({ 'config_name': config['name'], 'method': 'Lattice', 'time': lattice_time, 'memory': lattice_mem, 'tables_count': len(lattice_tables), 'accuracy': lattice_tables[0].accuracy if len(lattice_tables) > 0 else 0 }) print(f" Lattice - 時間: {lattice_time:.2f}秒, 內存: {lattice_mem:.2f}MB, 準確度: {lattice_tables[0].accuracy if len(lattice_tables) > 0 else 0}") except Exception as e: print(f" Lattice方法出錯: {str(e)}") # 測試Stream方法 try: stream_func = lambda: camelot.read_pdf( pdf_path, pages=page, flavor='stream', **config['params'] ) stream_tables, stream_time, stream_mem = measure_performance(stream_func) results.append({ 'config_name': config['name'], 'method': 'Stream', 'time': stream_time, 'memory': stream_mem, 'tables_count': len(stream_tables), 'accuracy': stream_tables[0].accuracy if len(stream_tables) > 0 else 0 }) print(f" Stream - 時間: {stream_time:.2f}秒, 內存: {stream_mem:.2f}MB, 準確度: {stream_tables[0].accuracy if len(stream_tables) > 0 else 0}") except Exception as e: print(f" Stream方法出錯: {str(e)}") # 查找最佳性能配置 if results: # 按準確度排序 accuracy_best = sorted(results, key=lambda x: x['accuracy'], reverse=True)[0] print(f"\n最高準確度配置: {accuracy_best['config_name']} / {accuracy_best['method']}") print(f" 準確度: {accuracy_best['accuracy']:.2f}, 耗時: {accuracy_best['time']:.2f}秒") # 按時間排序 time_best = sorted(results, key=lambda x: x['time'])[0] print(f"\n最快配置: {time_best['config_name']} / {time_best['method']}") print(f" 耗時: {time_best['time']:.2f}秒, 準確度: {time_best['accuracy']:.2f}") # 按內存使用排序 memory_best = sorted(results, key=lambda x: x['memory'])[0] print(f"\n最低內存配置: {memory_best['config_name']} / {memory_best['method']}") print(f" 內存: {memory_best['memory']:.2f}MB, 準確度: {memory_best['accuracy']:.2f}") # 綜合考慮速度和準確度的最佳配置 balanced = sorted(results, key=lambda x: (1/x['accuracy']) * x['time'])[0] print(f"\n平衡配置: {balanced['config_name']} / {balanced['method']}") print(f" 準確度: {balanced['accuracy']:.2f}, 耗時: {balanced['time']:.2f}秒") return balanced return None # 使用示例 best_config = optimize_camelot_performance("sample_report.pdf")
8. 比較與其他工具的差異
8.1 Camelot vs. PyPDF2/PyPDF4
def compare_with_pypdf(pdf_path, page=0): """比較Camelot與PyPDF2的提取能力""" import PyPDF2 print("\n===== PyPDF2提取結果 =====") try: # 使用PyPDF2提取文本 with open(pdf_path, 'rb') as file: reader = PyPDF2.PdfReader(file) if page < len(reader.pages): text = reader.pages[page].extract_text() print(f"提取的文本 ({len(text)} 字符):") print(text[:500] + "..." if len(text) > 500 else text) print("\nPyPDF2無法識別表格結構,只能提取純文本") else: print(f"頁碼 {page} 超出范圍") except Exception as e: print(f"PyPDF2提取出錯: {str(e)}") print("\n===== Camelot提取結果 =====") try: # 使用Camelot提取表格 tables = camelot.read_pdf(pdf_path, pages=str(page+1)) # Camelot頁碼從1開始 print(f"檢測到 {len(tables)} 個表格") if len(tables) > 0: table = tables[0] print(f"表格維度: {table.shape}") print(f"準確度: {table.accuracy}") print("\n表格預覽:") print(table.df.head().to_string()) print("\nCamelot可以識別表格結構,保留行列關系") except Exception as e: print(f"Camelot提取出錯: {str(e)}") return None # 使用示例 compare_with_pypdf("financial_data.pdf")
8.2 Camelot vs. Tabula
def compare_with_tabula(pdf_path, page='1'): """比較Camelot與Tabula的表格提取能力""" try: import tabula except ImportError: print("請安裝tabula-py: pip install tabula-py") return print("\n===== Tabula提取結果 =====") try: # 使用Tabula提取表格 tabula_tables = tabula.read_pdf(pdf_path, pages=page) print(f"檢測到 {len(tabula_tables)} 個表格") if len(tabula_tables) > 0: tabula_df = tabula_tables[0] print(f"表格維度: {tabula_df.shape}") print("\n表格預覽:") print(tabula_df.head().to_string()) except Exception as e: print(f"Tabula提取出錯: {str(e)}") print("\n===== Camelot提取結果 =====") try: # 使用Camelot提取表格 camelot_tables = camelot.read_pdf(pdf_path, pages=page) print(f"檢測到 {len(camelot_tables)} 個表格") if len(camelot_tables) > 0: camelot_df = camelot_tables[0].df print(f"表格維度: {camelot_df.shape}") print(f"準確度: {camelot_tables[0].accuracy}") print("\n表格預覽:") print(camelot_df.head().to_string()) except Exception as e: print(f"Camelot提取出錯: {str(e)}") # 比較結果 if 'tabula_tables' in locals() and 'camelot_tables' in locals(): if len(tabula_tables) > 0 and len(camelot_tables) > 0: tabula_df = tabula_tables[0] camelot_df = camelot_tables[0].df print("\n===== 比較結果 =====") print(f"Tabula表格大小: {tabula_df.shape}") print(f"Camelot表格大小: {camelot_df.shape}") # 檢查是否提取了相同的列數 if tabula_df.shape[1] != camelot_df.shape[1]: print(f"列數不同: Tabula={tabula_df.shape[1]}, Camelot={camelot_df.shape[1]}") print("這可能表明其中一個工具更好地識別了表格結構") # 檢查是否提取了相同的行數 if tabula_df.shape[0] != camelot_df.shape[0]: print(f"行數不同: Tabula={tabula_df.shape[0]}, Camelot={camelot_df.shape[0]}") print("這可能表明其中一個工具更好地識別了表格邊界") return None # 使用示例 compare_with_tabula("complex_table.pdf")
8.3 Camelot vs. pdfplumber
def compare_with_pdfplumber(pdf_path, page=0): """比較Camelot與pdfplumber的表格提取能力""" try: import pdfplumber except ImportError: print("請安裝pdfplumber: pip install pdfplumber") return print("\n===== pdfplumber提取結果 =====") try: # 使用pdfplumber提取表格 with pdfplumber.open(pdf_path) as pdf: if page < len(pdf.pages): plumber_page = pdf.pages[page] plumber_tables = plumber_page.extract_tables() print(f"檢測到 {len(plumber_tables)} 個表格") if len(plumber_tables) > 0: plumber_table = plumber_tables[0] plumber_df = pd.DataFrame(plumber_table[1:], columns=plumber_table[0]) print(f"表格維度: {plumber_df.shape}") print("\n表格預覽:") print(plumber_df.head().to_string()) else: print(f"頁碼 {page} 超出范圍") except Exception as e: print(f"pdfplumber提取出錯: {str(e)}") print("\n===== Camelot提取結果 =====") try: # 使用Camelot提取表格 camelot_tables = camelot.read_pdf(pdf_path, pages=str(page+1)) # Camelot頁碼從1開始 print(f"檢測到 {len(camelot_tables)} 個表格") if len(camelot_tables) > 0: camelot_df = camelot_tables[0].df print(f"表格維度: {camelot_df.shape}") print(f"準確度: {camelot_tables[0].accuracy}") print("\n表格預覽:") print(camelot_df.head().to_string()) except Exception as e: print(f"Camelot提取出錯: {str(e)}") return None # 使用示例 compare_with_pdfplumber("annual_report.pdf")
9. 故障排除與常見問題
9.1 解決提取問題
def diagnose_extraction_issues(pdf_path, page='1'): """診斷和解決表格提取問題""" # 檢查PDF是否可訪問 try: with open(pdf_path, 'rb') as f: pass except Exception as e: print(f"無法訪問PDF文件: {str(e)}") return # 檢查是否為掃描PDF import fitz # PyMuPDF try: doc = fitz.open(pdf_path) page_obj = doc[int(page) - 1] text = page_obj.get_text() if len(text.strip()) < 50: print("檢測到可能是掃描PDF或圖像PDF") print("建議: 使用OCR軟件先將PDF轉換為可搜索的PDF") # 檢查頁面旋轉 rotation = page_obj.rotation if rotation != 0: print(f"頁面旋轉了 {rotation} 度") print("建議: 使用PyMuPDF或其他工具先將PDF頁面旋轉到正常方向") except Exception as e: print(f"檢查PDF格式時出錯: {str(e)}") # 嘗試使用不同的提取方法 print("\n嘗試使用不同的Camelot配置...") # 嘗試Lattice方法 try: print("\n使用Lattice方法:") lattice_tables = camelot.read_pdf( pdf_path, pages=page, flavor='lattice' ) if len(lattice_tables) > 0: print(f"成功提取 {len(lattice_tables)} 個表格") print(f"準確度: {lattice_tables[0].accuracy}") else: print("未檢測到表格") print("建議: 嘗試調整line_scale參數和表格區(qū)域") except Exception as e: print(f"Lattice方法出錯: {str(e)}") # 嘗試Stream方法 try: print("\n使用Stream方法:") stream_tables = camelot.read_pdf( pdf_path, pages=page, flavor='stream' ) if len(stream_tables) > 0: print(f"成功提取 {len(stream_tables)} 個表格") print(f"準確度: {stream_tables[0].accuracy}") else: print("未檢測到表格") print("建議: 嘗試指定表格區(qū)域") except Exception as e: print(f"Stream方法出錯: {str(e)}") # 建議 print("\n==== 一般建議 ====") print("1. 如果兩種方法都失敗,嘗試指定表格區(qū)域") print("2. 對于有明顯表格線的PDF,優(yōu)先使用Lattice方法并調整line_scale") print("3. 對于無表格線的PDF,優(yōu)先使用Stream方法并調整邊緣容忍度") print("4. 嘗試將PDF頁面轉換為圖像,然后使用OpenCV預處理后再提取") print("5. 如果是掃描PDF,考慮先使用OCR軟件進行處理") return None # 使用示例 diagnose_extraction_issues("problematic_report.pdf")
9.2 常見錯誤及解決方案
def common_errors_guide(): """提供Camelot常見錯誤的解決指南""" errors = { "ImportError: No module named 'cv2'": { "原因": "缺少OpenCV依賴", "解決方案": "運行 pip install opencv-python" }, "File does not exist": { "原因": "文件路徑錯誤", "解決方案": "檢查文件路徑是否正確,包括大小寫和空格" }, "OCR engine not reachable": { "原因": "嘗試使用OCR但未安裝Tesseract", "解決方案": "安裝Tesseract OCR并確保它在系統(tǒng)路徑中" }, "Invalid page range specified": { "原因": "指定的頁碼超出了PDF范圍", "解決方案": "確保頁碼在文檔頁數范圍內,Camelot的頁碼從1開始" }, "Unable to process background": { "原因": "在處理背景時遇到問題,通常與GhostScript有關", "解決方案": "檢查GhostScript是否正確安裝,或嘗試禁用背景處理 (process_background=False)" }, "No tables found on page": { "原因": "Camelot無法在指定頁面檢測到表格", "解決方案": [ "1. 嘗試另一種提取方法 (lattice 或 stream)", "2. 手動指定表格區(qū)域", "3. 調整檢測參數 (line_scale, edge_tol等)", "4. 檢查PDF是否為掃描版,如果是請先使用OCR處理" ] } } print("==== Camelot常見錯誤及解決方案 ====\n") for error, info in errors.items(): print(f"錯誤: {error}") print(f"原因: {info['原因']}") if isinstance(info['解決方案'], list): print("解決方案:") for solution in info['解決方案']: print(f" {solution}") else: print(f"解決方案: {info['解決方案']}") print() print("==== 一般性建議 ====") print("1. 始終使用最新版本的Camelot和其依賴") print("2. 對于復雜表格,嘗試分析表格結構后手動指定區(qū)域") print("3. 使用可視化工具驗證表格邊界檢測") print("4. 對于大型PDF,考慮按批次處理頁面") print("5. 如果一種提取方法失敗,嘗試另一種方法") return None # 使用示例 common_errors_guide()
10. 總結與展望
Camelot作為專業(yè)的PDF表格提取工具,為數據分析師和開發(fā)者提供了強大的解決方案。通過本文介紹的技術,您可以:
- 精確提取PDF文檔中的表格數據,包括復雜表格和掃描文檔
- 根據不同表格類型選擇最適合的提取方法(Lattice或Stream)
- 清洗和處理提取的表格數據,解決合并單元格等常見問題
- 集成到數據分析流程中,與pandas、matplotlib等工具無縫配合
- 優(yōu)化提取性能,處理大型PDF文檔
- 創(chuàng)建自動化數據提取管道,批量處理多個PDF文件
隨著數據分析需求的不斷增長,PDF表格數據提取的重要性也日益凸顯。未來,我們可以期待以下發(fā)展趨勢:
- 結合深度學習改進表格檢測和結構理解
- 提升對復雜布局和多語言表格的處理能力
- 更智能的數據類型識別和語義理解
- 與自動化工作流程平臺的深度集成
- 云服務和API接口的普及,使表格提取更加便捷
掌握PDF表格數據提取技術,不僅能夠提高工作效率,還能從過去被"鎖定"在PDF文件中的數據中挖掘出寶貴的商業(yè)價值。希望本文能夠幫助您充分利用Camelot的強大功能,高效準確地從PDF文檔中獲取表格數據。
參考資源
Camelot官方文檔:https://camelot-py.readthedocs.io/
Camelot GitHub倉庫:https://github.com/camelot-dev/camelot
pandas官方文檔:https://pandas.pydata.org/docs/
Ghostscript:https://www.ghostscript.com/
OpenCV:https://opencv.org/
附錄:表格提取參數參考
# Lattice方法參數參考 lattice_params = { 'line_scale': 15, # 線條檢測靈敏度,值越高檢測越少的線 'copy_text': [], # 要從PDF復制的文本區(qū)域 'shift_text': [], # 要移動的文本區(qū)域 'line_margin': 2, # 線條檢測間隔容忍度 'joint_tol': 2, # 連接點容忍度 'threshold_blocksize': 15, # 自適應閾值的塊大小 'threshold_constant': -2, # 自適應閾值的常數 'iterations': 0, # 形態(tài)學操作的迭代次數 'resolution': 300, # PDF-to-PNG轉換的DPI 'process_background': False, # 是否處理背景 'table_areas': [], # 表格區(qū)域列表,格式為[x1,y1,x2,y2] 'table_regions': [] # 表格區(qū)域名稱 } # Stream方法參數參考 stream_params = { 'table_areas': [], # 表格區(qū)域列表 'columns': [], # 列坐標 'row_tol': 2, # 行容忍度 'column_tol': 0, # 列容忍度 'edge_tol': 50, # 邊緣容忍度 'split_text': False, # 是否拆分文本,實驗性功能 'flag_size': False, # 是否標記文本大小 'strip_text': '', # 要從文本中刪除的字符 'edge_segment_counts': 50, # 用于檢測表格邊緣的線段數 'min_columns': 1, # 最小列數 'max_columns': 0, # 最大列數,0表示無限制 'split_columns': False, # 是否拆分列,實驗性功能 'process_background': False, # 是否處理背景 'line_margin': 2, # 線條檢測間隔容忍度 'joint_tol': 2, # 連接點容忍度 'threshold_blocksize': 15, # 自適應閾值的塊大小 'threshold_constant': -2, # 自適應閾值的常數 'iterations': 0, # 形態(tài)學操作的迭代次數 'resolution': 300 # PDF-to-PNG轉換的DPI }
通過掌握Camelot的使用技巧,您將能夠高效地從各種PDF文檔中提取表格數據,為數據分析和自動化流程提供有力支持。
以上就是Python使用Camelot從PDF中精準獲取表格數據的詳細內容,更多關于Python從PDF中精準獲取數據的資料請關注腳本之家其它相關文章!
相關文章
Pycharm創(chuàng)建項目時如何自動添加頭部信息
這篇文章主要介紹了Pycharm創(chuàng)建項目時 自動添加頭部信息,需要的朋友可以參考下2019-11-11用Python展示動態(tài)規(guī)則法用以解決重疊子問題的示例
這篇文章主要介紹了用Python展示動態(tài)規(guī)則法用以解決重疊子問題的一個棋盤游戲的示例,動態(tài)規(guī)劃常常適用于有重疊子問題和最優(yōu)子結構性質的問題,且耗時間往往遠少于樸素解法,需要的朋友可以參考下2015-04-04Python Web框架Flask中使用百度云存儲BCS實例
這篇文章主要介紹了Python Web框架Flask中使用百度云存儲BCS實例,本文調用了百度云存儲Python SDK中的相關類,需要的朋友可以參考下2015-02-02