table-extractor
БесплатноБез исполняемых скриптовНе проверенExtract tables from PDFs with high accuracy using camelot. Handles complex table structures including merged cells, multi-line rows, and spanning headers. Use…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Table Extractor
Overview
Extract tables from PDF documents using camelot-py (2.0). Camelot offers lattice (ruled tables), stream and network (whitespace-based), and hybrid parsers, plus an optional neural ml flavor for borderless tables, and handles multi-line rows and spanning headers with some post-processing. Outputs clean DataFrames that can be exported to CSV, Excel, or JSON.
Instructions
When a user asks you to extract tables from a PDF, follow this process:
Step 1: Install and verify dependencies
pip install camelot-py pandas
python -c "import camelot; print(camelot.__version__)"
Since Camelot 1.0 Ghostscript is no longer required: pages are rasterized with pdfium, which installs with pip. Install the ghostscript extra (plus the Ghostscript system package) only if you want that backend. If import cv2 fails and the environment also has the full opencv-python, uninstall opencv-python; Camelot needs opencv-python-headless. Camelot reads text-based PDFs only; for scans, run ocrmypdf first (or install the ocr/ml extras and use flavor="ml").
If Camelot cannot be installed, fall back to pdfplumber:
pip install pdfplumber pandas
Step 2: Inspect the PDF to locate tables
import camelot
# Quick scan: how many tables are in the document?
tables = camelot.read_pdf("document.pdf", pages="all", flavor="lattice")
print(f"Found {len(tables)} tables using lattice detection")
# If no tables found, try stream detection (for borderless tables).
# flavor="auto" lets Camelot probe the first page and pick lattice or network.
if len(tables) == 0:
tables = camelot.read_pdf("document.pdf", pages="all", flavor="stream")
print(f"Found {len(tables)} tables using stream detection")
# Summary of each table
for i, table in enumerate(tables):
print(f"\nTable {i}: {table.shape[0]} rows x {table.shape[1]} cols (page {table.page})")
print(f"Accuracy: {table.accuracy:.1f}% whitespace: {table.whitespace:.1f}%")
print(table.parsing_report) # also holds a 0-1 "confidence" score
print(table.df.head(3))
Step 3: Choose the right extraction flavor
Lattice flavor (for tables with visible borders/gridlines):
tables = camelot.read_pdf(
"document.pdf",
pages="1,2,3", # Specific pages
flavor="lattice",
line_scale=40, # Adjust line detection sensitivity
process_background=True # Detect lines on colored backgrounds
)
Stream flavor (for borderless tables, whitespace-separated). flavor="network" and flavor="hybrid" are alternative text-alignment parsers worth trying when stream splits columns badly:
tables = camelot.read_pdf(
"document.pdf",
pages="1",
flavor="stream",
edge_tol=50, # Tolerance for edge detection
row_tol=10, # Tolerance for grouping text into rows
columns=["72,200,350,500"] # Manual column boundaries if auto-detect fails
)
Step 4: Clean and process extracted tables
import pandas as pd
for i, table in enumerate(tables):
df = table.df
# Promote first row to header if it contains column names
if df.iloc[0].str.match(r'^[A-Za-z]').all():
df.columns = df.iloc[0]
df = df[1:].reset_index(drop=True)
# Clean whitespace and newlines within cells
df = df.apply(lambda col: col.str.strip().str.replace(r'\n', ' ', regex=True))
# Remove completely empty rows
df = df.dropna(how='all').replace('', pd.NA).dropna(how='all')
# Convert numeric columns
for col in df.columns:
try:
df[col] = pd.to_numeric(df[col].str.replace(',', '').str.replace('$', ''))
except (ValueError, AttributeError):
pass # Keep as string
print(f"\nCleaned Table {i}:")
print(df.head())
Step 5: Handle complex table structures
Merged cells and spanning headers:
# Forward-fill merged cells (common in row headers)
df.iloc[:, 0] = df.iloc[:, 0].replace('', pd.NA).ffill()
# Handle multi-level column headers
if df.iloc[0:2].apply(lambda x: x.str.len().mean()).mean() < 20:
# Combine first two rows as multi-level header
new_cols = df.iloc[0] + " - " + df.iloc[1]
df.columns = new_cols.str.strip(" - ")
df = df[2:].reset_index(drop=True)
Tables spanning multiple pages:
# Extract from all pages and concatenate
all_tables = camelot.read_pdf("document.pdf", pages="all", flavor="lattice")
# Group tables that are continuations (same column count)
groups = {}
for t in all_tables:
key = t.shape[1]
groups.setdefault(key, []).append(t.df)
for col_count, dfs in groups.items():
combined = pd.concat(dfs, ignore_index=True)
# Remove duplicate header rows that appear at page breaks
combined = combined[~combined.duplicated(keep='first')]
Step 6: Export the results
# CSV (one file per table)
for i, table in enumerate(tables):
table.df.to_csv(f"table
Установить table-extractor в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл table-extractor?
Extract tables from PDFs with high accuracy using camelot. Handles complex table structures including merged cells, multi-line rows, and spanning headers. Use when a user asks to extract a table from a PDF, pull tabular data from a document, convert PDF tables to CSV or Excel, or parse structured tables from reports.
Как установить скилл table-extractor?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл table-extractor запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic