Python 库 unstructured:高效转换 PDF、Word 等非结构化数据
unstructured 是一个强大的 Python 开源库,专门用于处理和预处理非结构化数据(如 PDF、Word 文档、HTML、图片等),将其转换为结构化格式。这对于下游的机器学习(ML)或大语言模型(LLM)任务至关重要。它提供模块化的组件(称为'bricks'),支持文档分区、清理和格式化,广泛应用于数据管道、RAG(检索增强生成)系统和文档分析。
安装与环境配置
基础依赖
首先确保你的 Python 版本在 3.8+(推荐 3.9+)。核心依赖包括 beautifulsoup4(HTML 解析)、lxml(XML 处理)和 nltk(文本处理)。
pip install unstructured
系统级依赖
如果你需要处理 PDF 或图片,本地环境还需要安装额外的工具:
- Tesseract:用于 OCR 识别。
- Poppler:用于 PDF 处理。
- Pandoc:处理 EPUB、RTF 等格式。
以 Linux 为例,安装 libmagic 用于文件类型检测:
# Ubuntu/Debian
sudo apt-get install libmagic1
# macOS
brew install libmagic
对于特定文档类型,可以安装可选依赖以减少开销:
pip install "unstructured[docx]"
pip install "unstructured[local-inference]" # 包含 PDF 和图片处理的完整依赖
Docker 部署
如果不想污染本地环境,可以使用官方 Docker 镜像:
docker pull downloads.unstructured.io/unstructured-io/unstructured:latest
docker run -dt --name unstructured downloads.unstructured.io/unstructured-io/unstructured:latest
docker exec -it unstructured bash
核心功能与用法
unstructured 的核心逻辑是通过'bricks'处理文档,主要分为分区(Partitioning)、清理(Cleaning)和格式化(Staging)三大类。
1. 分区(Partitioning)
这是最关键的一步,将文档拆分为标题、段落、列表、表格等结构化元素。partition 函数会自动检测文件类型并调用相应的处理器。
from unstructured.partition.auto import partition
# 自动检测并解析 PDF 文件
elements = partition(filename="example.pdf")
for element in elements[:]:
()

