关于 document-parsers
document-parsers 是面向文档处理与 RAG 工作流的解析技能,提供 PDF、DOCX、HTML、Markdown 和 TXT 的脚本与模板。它可按文档类型选择解析器,并支持表格提取、元数据处理和分块。
主要功能
- 01支持多种文档格式解析
- 02提供多种 PDF 后端
- 03提取表格与元数据
- 04文档分块及结构化输出
- 05包含研究与法律文档示例
适用场景
- 01为 RAG 管线准备文档分块
- 02从 PDF 提取文本和表格
- 03批量处理多格式文档
- 04解析研究论文或法律文件
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ vanman2024/ ai-dev-marketplace --skill document-parsers安装后在 Claude Code 中输入/document-parsers确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
examples/parse-legal-document.pyparse-research-paper.pyscripts/parse-docx.pyparse-html.pyparse-pdf.pysetup-llamaparse.shsetup-unstructured.shtemplates/multi-format-parser.pytable-extraction.py详细介绍
文档解析器
用途: 使用行业标准库和 AI 驱动的解析工具,自主解析并提取多种文档格式(PDF、DOCX、HTML、Markdown)中的内容。
激活条件:
- 构建 RAG(检索增强生成)流水线
- 从文档中提取文本、表格或元数据
- 处理大型文档集合
- 将文档转换为结构化格式
- 处理包含表格和复杂版式的 PDF
- 对扫描文档进行 OCR
- 将文档分块以生成向量嵌入
- 构建文档搜索系统
关键资源:
scripts/setup-llamaparse.sh- 安装并配置 LlamaParse(AI 驱动的解析)scripts/setup-unstructured.sh- 安装 Unstructured.io 库scripts/parse-pdf.py- 支持多种后端选项的实用 PDF 解析器scripts/parse-docx.py- DOCX 文档解析器scripts/parse-html.py- 将 HTML 转换为结构化文本的解析器templates/multi-format-parser.py- 通用文档解析器模板templates/table-extraction.py- 专用表格提取模板examples/parse-research-paper.py- 带引文的研究论文解析examples/parse-legal-document.py- 带章节的法律文档解析
解析器比较与选择指南
1. LlamaParse(AI 驱动的高级服务)
最适合:
- 包含表格、图表和混合版式的复杂 PDF
- 需要 OCR 的扫描文档
- 准确性至关重要的文档
- 多栏版式和科学论文
- 财务报告和发票
优点:
- AI 驱动的版式理解
- 表格提取准确度出色
- 内置 OCR 支持
- 可处理复杂格式
- 结构化输出(Markdown/JSON)
缺点:
- 需要 API 密钥(付费服务)
- API 速率限制
- 依赖网络
- 速度比本地解析器慢
文档: https://docs.cloud.llamaindex.ai/llamaparse
设置:
./scripts/setup-llamaparse.sh
使用模式:
from llama_parse import LlamaParse
parser = LlamaParse(
api_key="llx-...",
result_type="markdown", # or "text"
language="en",
verbose=True
)
documents = parser.load_data("document.pdf")
for doc in documents:
print(doc.text)
2. Unstructured.io(本地处理)
最适合:
- 批量处理大量文档
- 支持多种格式(PDF、DOCX、HTML、PPTX、图像)
- 无需依赖 API 的本地处理
- 结构化元素提取
- 生产环境中的 RAG 流水线
优点:
- 开源且免费
- 支持多种格式
- 在本地运行(无需 API 密钥)
- 表格检测效果良好
- 基于元素的分块
缺点:
- 需要系统依赖项(poppler、tesseract)
- 安装复杂
- 处理复杂版式时不如 LlamaParse 准确
文档: https://unstructured-io.github.io/unstructured/
设置:
./scripts/setup-unstructured.sh
使用模式:
from unstructured.partition.auto import partition
elements = partition("document.pdf")
for element in elements:
print(f"{element.category}: {element.text}")
3. PyPDF2(简单的 PDF 文本提取)
最适合:
- 简单的文本型 PDF
- 快速原型开发
- 元数据提取
- PDF 操作(合并、拆分)
优点:
- 纯 Python(无依赖项)
- 快速轻量
- 适用于简单 PDF
- 持续维护
缺点:
- 表格提取效果差
- 难以处理复杂版式
- 不支持 OCR
- 格式保留能力有限
文档: https://github.com/py-pdf/pypdf2
设置:
pip install pypdf2
使用模式:
from PyPDF2 import PdfReader
reader = PdfReader("document.pdf")
for page in reader.pages:
print(page.extract_text())
4. PDFPlumber(高级 PDF 分析)
最适合:
- 从 PDF 中提取表格
- 含表格数据的 PDF
- 财务报表和报告
- 基于坐标的提取
优点:
- 表格提取效果出色
- 可视化调试工具
- 坐标级控制
- 元数据和版式信息
缺点:
- 速度比 PyPDF2 慢
- 需要 pdfminer.six 依赖项
- 不支持 OCR
文档: https://github.com/jsvine/pdfplumber
设置:
pip install pdfplumber
使用模式:
import pdfplumber
with pdfplumber.open("document.pdf") as pdf:
for page in pdf.pages:
tables = page.extract_tables()
text = page.extract_text()
5. python-docx(Word 文档)
最适合:
- Microsoft Word(.docx)文档
- 提取段落、表格和页眉
- 文档元数据
- 基于模板生成文档
优点:
- 原生支持 DOCX
- 保留结构(段落、表格、分节)
- 可访问样式和格式
- 还可以编写或修改 DOCX
缺点:
- 仅适用于 .docx(不适用于 .doc)
- 图像提取能力有限
文档: https://github.com/python-openxml/python-docx
设置:
pip install python-docx
使用模式:
from docx import Document
doc = Document("document.docx")
for para in doc.paragraphs:
print(para.text)
for table in doc.tables:
for row in table.rows:
print([cell.text for cell in row.cells])
决策矩阵
| 用例 | 推荐解析器 | 替代方案 |
|---|---|---|
| 简单的 PDF 文本提取 | PyPDF2 | Unstructured |
| 包含表格的复杂 PDF | LlamaParse | PDFPlumber |
| 扫描文档(OCR) | LlamaParse | Unstructured + Tesseract |
| Word 文档(.docx) | python-docx | Unstructured |
| HTML 转文本 | parse-html.py | Unstructured |
| 多格式批量处理 | Unstructured | Multi-format-parser |
| 表格提取 | PDFPlumber | LlamaParse |
| 研究论文 | LlamaParse | Unstructured |
| 法律文档 | LlamaParse | PDFPlumber |
| 生产环境 RAG 流水线 | Unstructured | LlamaParse |
功能脚本
1. 解析 PDF(scripts/parse-pdf.py)
支持多个后端的命令行 PDF 解析器:
# Using PyPDF2 (default)
python scripts/parse-pdf.py document.pdf
# Using PDFPlumber (better for tables)
python scripts/parse-pdf.py document.pdf --backend pdfplumber
# Using LlamaParse (AI-powered)
python scripts/parse-pdf.py document.pdf --backend llamaparse --api-key llx-...
# Output to file
python scripts/parse-pdf.py document.pdf --output output.txt
# Extract tables as JSON
python scripts/parse-pdf.py document.pdf --backend pdfplumber --tables-only --output tables.json
功能:
- 支持多个后端(PyPDF2、PDFPlumber、LlamaParse)
- 表格提取
- 元数据提取
- 页面范围选择
- JSON/Text 输出格式
2. 解析 DOCX(scripts/parse-docx.py)
保留结构的 Word 文档解析器:
# Basic extraction
python scripts/parse-docx.py document.docx
# Extract with structure
python scripts/parse-docx.py document.docx --preserve-structure
# Extract tables only
python scripts/parse-docx.py document.docx --tables-only
# Output as JSON
python scripts/parse-docx.py document.docx --output output.json --format json
功能:
- 提取段落及其样式
- 表格提取
- 页眉/页脚提取
- 元数据(作者、创建日期等)
- 结构化 JSON 输出
3. 解析 HTML(scripts/parse-html.py)
将 HTML 转换为干净文本的工具:
# Basic HTML parsing
python scripts/parse-html.py document.html
# From URL
python scripts/parse-html.py https://example.com/article
# Preserve links
python scripts/parse-html.py document.html --preserve-links
# Extract specific selector
python scripts/parse-html.py document.html --selector "article.content"
功能:
- 提取干净文本(移除脚本和样式)
- 保留链接
- 支持 CSS 选择器
- 获取 URL 内容
- 可选择输出 Markdown
模板
多格式解析器(templates/multi-format-parser.py)
可处理多种格式并自动检测格式的通用解析器:
from multi_format_parser import MultiFormatParser
parser = MultiFormatParser(
llamaparse_api_key="llx-...", # Optional
use_ocr=True,
chunk_size=1000
)
# Automatic format detection
result = parser.parse_file("document.pdf")
print(result.text)
print(result.metadata)
print(result.tables)
# Batch processing
results = parser.parse_directory("./documents/")
for filename, result in results.items():
print(f"{filename}: {len(result.text)} characters")
支持:
- PDF、DOCX、HTML、Markdown、TXT
- 为 RAG 自动分块
- 元数据提取
- 提取所有格式中的表格
- 错误处理和回退方案
表格提取(templates/table-extraction.py)
采用多种策略的专用表格提取工具:
from table_extraction import TableExtractor
extractor = TableExtractor(
prefer_llamaparse=True,
fallback_to_pdfplumber=True
)
# Extract all tables from document
tables = extractor.extract_tables("financial_report.pdf")
for i, table in enumerate(tables):
print(f"Table {i + 1}:")
print(table.to_markdown()) # or .to_csv(), .to_json()
print(f"Confidence: {table.confidence}")
功能:
- 多种提取策略
- 自动回退
- 表格验证
- 格式转换(CSV、JSON、Markdown、DataFrame)
- 置信度评分
示例
研究论文解析(examples/parse-research-paper.py)
解析学术论文的完整示例:
# Extracts title, abstract, sections, citations, tables, figures
python examples/parse-research-paper.py paper.pdf --output paper.json
提取内容:
- 标题和作者
- 摘要
- 章节结构(引言、方法、结果等)
- 引用和参考文献
- 带标题的表格和图表
- 元数据(DOI、出版日期、期刊)
法律文档解析(examples/parse-legal-document.py)
用于法律文档的专用解析器:
# Extracts clauses, sections, definitions, parties
python examples/parse-legal-document.py contract.pdf --output contract.json
提取内容:
- 文档类型(合同、协议等)
- 相关各方
- 定义部分
- 编号条款和章节
- 签名栏
- 日期和截止期限
RAG 流水线集成
用于嵌入的文档分块
from multi_format_parser import MultiFormatParser
parser = MultiFormatParser(chunk_size=512, chunk_overlap=50)
result = parser.parse_file("document.pdf")
# Chunks ready for embedding
for chunk in result.chunks:
print(f"Chunk {chunk.id}: {chunk.text[:100]}...")
print(f"Metadata: {chunk.metadata}")
# Send to embedding model
批处理流水线
import glob
from multi_format_parser import MultiFormatParser
parser = MultiFormatParser()
# Process all documents in directory
for filepath in glob.glob("./documents/**/*", recursive=True):
try:
result = parser.parse_file(filepath)
# Store in vector database
store_embeddings(result.chunks)
print(f"✓ Processed {filepath}")
except Exception as e:
print(f"✗ Failed {filepath}: {e}")
最佳实践
解析器选择:
- 简单 PDF 从 PyPDF2 开始,必要时再升级
- 复杂布局使用 LlamaParse(预算允许时)
- 多格式生产系统使用 Unstructured
- 提取表格时专门使用 PDFPlumber
性能:
- 缓存解析结果,避免重复处理
- 多份文档使用批处理
- 对大型文档集考虑使用异步处理
- 监控 LlamaParse 的 API 速率限制
准确性:
- 验证表格提取结果
- 实施回退策略
- 记录解析错误以便调试
- 在可用时使用置信度分数
RAG 优化:
- 分块大小:嵌入使用 512-1024 个令牌
- 重叠:10-20%,以保留上下文
- 保留元数据(页码、章节),以便检索
- 清理提取的文本(移除页眉和页脚)
故障排除
PyPDF2 返回乱码文本:
- 尝试使用 PDFPlumber 或 LlamaParse
- PDF 可能使用了非标准编码
- 检查 PDF 是否为扫描件(需要 OCR)
Unstructured 安装失败:
- 安装系统依赖项:
sudo apt-get install poppler-utils tesseract-ocr - 在 macOS 上:
brew install poppler tesseract
LlamaParse API 错误:
- 确认 API 密钥正确
- 在控制面板中检查速率限制
- 确保文档大小未超出限制
表格提取时遗漏列:
- 尝试使用其他解析器(PDFPlumber 或 LlamaParse)
- 调整表格检测设置
- 手动验证表格结构
DOCX 解析失败:
- 确保文件为 .docx,而不是 .doc
- 检查文件是否损坏
- 尝试使用 LibreOffice 将文件转换为 .docx
依赖项
核心:
pip install pypdf2 pdfplumber python-docx beautifulsoup4 lxml markdown
可选(Unstructured):
pip install unstructured[local-inference]
sudo apt-get install poppler-utils tesseract-ocr # Linux
brew install poppler tesseract # macOS
可选(LlamaParse):
pip install llama-parse
# Requires API key from https://cloud.llamaindex.ai
支持的格式: PDF、DOCX、HTML、Markdown、TXT 解析器: LlamaParse、Unstructured.io、PyPDF2、PDFPlumber、python-docx 版本: 1.0.0