Home
cd ../playbooks
Data & ReportingAdvanced

Data Extraction Assistant

Extract structured data from PDFs, Word docs, emails, and HTML using the unstructured library.

10 minutes
By communitySource
#extraction#data#unstructured

Your data is trapped in PDFs, Word docs, emails, and HTML pages. Manually copying it into spreadsheets is mind-numbing, error-prone, and completely unscalable.

Who it's for: operations teams processing documents into databases, analysts pulling data from unstructured sources, developers building document processing pipelines, compliance teams extracting information from filings, anyone manually copy-pasting from PDFs

Example

"Extract all vendor names, amounts, and dates from these 200 PDF invoices" → Structured CSV output with consistent formatting, regardless of whether the source was a PDF, Word doc, or email — ready to import into your database

CLAUDE.md Template

New here? 3-minute setup guide → | Already set up? Copy the template below.

Or install from your terminal:
npx ccplaybooks add data-extractor
# Data Extractor

## Overview

This workflow enables extraction of structured data from any document format using **unstructured** - a unified library for processing PDFs, Word docs, emails, HTML, and more. Get consistent, structured output regardless of input format.

## How to Use

1. Provide the document to process
2. Optionally specify extraction options
3. I'll extract structured elements with metadata

Get new playbooks like this one

One email a week with new Claude Code workflows. Free, like everything here.

No spam. Unsubscribe anytime.

README.md

What This Does

This workflow enables extraction of structured data from any document format using unstructured - a unified library for processing PDFs, Word docs, emails, HTML, and more. Get consistent, structured output regardless of input format.


Quick Start

Step 1: Create a Project Folder

mkdir -p ~/Documents/DataExtractor

Step 2: Download the Template

Click Download above, then:

mv ~/Downloads/CLAUDE.md ~/Documents/DataExtractor/

Step 3: Start Working

cd ~/Documents/DataExtractor
claude

How to Use

  1. Provide the document to process
  2. Optionally specify extraction options
  3. I'll extract structured elements with metadata

Example prompts:

  • "Extract all text and tables from this PDF"
  • "Parse this email and get the body, attachments, and metadata"
  • "Convert this HTML page to structured elements"
  • "Extract data from these mixed-format documents"

Best Practices

  1. Choose Strategy Wisely: "fast" for speed, "hi_res" for accuracy
  2. Enable Table Detection: For documents with tables
  3. Specify Language: For better OCR on non-English docs
  4. Chunk for RAG: Use semantic chunking for AI applications
  5. Handle Errors: Some formats may fail gracefully

Examples

Example 1: Research Paper Extraction

from unstructured.partition.pdf import partition_pdf
from unstructured.chunking.title import chunk_by_title

def extract_paper(pdf_path):
    """Extract structured data from research paper."""
    
    elements = partition_pdf(
        filename=pdf_path,
        strategy="hi_res",
        infer_table_structure=True,
        include_page_breaks=True
    )
    
    paper = {
        'title': None,
        'abstract': None,
        'sections': [],
        'tables': [],
        'references': []
    }
    
    # Find title (usually first Title element)
    for element in elements:
        if element.category == "Title" and not paper['title']:
            paper['title'] = element.text
            break
    
    # Extract tables
    for element in elements:
        if element.category == "Table":
            paper['tables'].append({
                'page': element.metadata.page_number,
                'content': element.text,
                'html': element.metadata.text_as_html if hasattr(element.metadata, 'text_as_html') else None
            })
    
    # Chunk into sections
    chunks = chunk_by_title(elements, max_characters=2000)
    
    current_section = None
    for chunk in chunks:
        if chunk.category == "Title":
            paper['sections'].append({
                'title': chunk.text,
                'content': ''
            })
        elif paper['sections']:
            paper['sections'][-1]['content'] += chunk.text + '\n'
    
    return paper

paper = extract_paper('research_paper.pdf')
print(f"Title: {paper['title']}")
print(f"Tables: {len(paper['tables'])}")
print(f"Sections: {len(paper['sections'])}")

Example 2: Invoice Data Extraction

from unstructured.partition.auto import partition
import re

def extract_invoice_data(file_path):
    """Extract key data from invoice."""
    
    elements = partition(file_path, strategy="hi_res")
    
    # Combine all text
    full_text = '\n'.join([e.text for e in elements])
    
    invoice = {
        'invoice_number': None,
        'date': None,
        'total': None,
        'vendor': None,
        'line_items': [],
        'tables': []
    }
    
    # Extract patterns
    inv_match = re.search(r'Invoice\s*#?\s*:?\s*(\w+[-\w]*)', full_text, re.I)
    if inv_match:
        invoice['invoice_number'] = inv_match.group(1)
    
    date_match = re.search(r'Date\s*:?\s*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})', full_text, re.I)
    if date_match:
        invoice['date'] = date_match.group(1)
    
    total_match = re.search(r'Total\s*:?\s*\$?([\d,]+\.?\d*)', full_text, re.I)
    if total_match:
        invoice['total'] = float(total_match.group(1).replace(',', ''))
    
    # Extract tables
    for element in elements:
        if element.category == "Table":
            invoice['tables'].append(element.text)
    
    return invoice

invoice = extract_invoice_data('invoice.pdf')
print(f"Invoice #: {invoice['invoice_number']}")
print(f"Total: ${invoice['total']}")

Example 3: Document Corpus Builder

Limitations

  • Complex layouts may need manual review
  • OCR quality depends on image quality
  • Large files may need chunking
  • Some proprietary formats not supported
  • API rate limits for cloud processing

Installation

# Basic installation
pip install unstructured

# With all dependencies
pip install "unstructured[all-docs]"

# For PDF processing
pip install "unstructured[pdf]"

# For specific formats
pip install "unstructured[docx,pptx,xlsx]"

$Related Playbooks

Data & Reporting

Engagement Pattern Analyzer

Analyze which posts get saved vs liked vs replied to, find the patterns, and separate what your audience actually values from vanity engagement.

10 minutes
Intermediate
Data & Reporting

Eval Config

Configure content eval settings.

15 minutes
Intermediate
Data & Reporting

Eval Suite

Batch evaluate multiple content pieces.

15 minutes
Intermediate
Data & Reporting

Executive Dashboard

Design executive marketing dashboards.

15 minutes
Intermediate
Data & Reporting

Excel Automation Workflows

Automate Excel workflows including real-time control, VBA execution, and dashboard updates using xlwings.

10 minutes
Advanced
Data & Reporting

GEO Monthly Delta Report

Compare two GEO audits of the same site and generate a client progress report showing exactly what moved, by how much, and what is next

10 minutes
Intermediate
Data & Reporting

GEO Report PDF Renderer

Render a GEO audit markdown file into a styled client-ready PDF with a cover page, color-coded score tables, and severity callouts

10 minutes
Intermediate
Data & Reporting

GEO Client Report Generator

Turn AI-search audit findings into a client-ready GEO report with a weighted 0-100 readiness score and a three-tier action plan

10 minutes
Intermediate
Data & Reporting

Intelligence Report

Generate marketing intelligence briefings.

15 minutes
Intermediate
Data & Reporting

Interactive Dashboard Builder

Build self-contained HTML dashboards with Chart.js for data visualization

10 minutes
Intermediate
Data & Reporting

Funnel Metrics Analyst

Get a daily one-paragraph analysis of your funnel metrics — what moved, what's stalling, and what to do about it. An actual opinion, not a dashboard.

15 minutes
Advanced
Data & Reporting

Live Dashboard

Create live Looker Studio dashboards.

15 minutes
Intermediate

Browse all Data & Reporting playbooks →