为什么需要 unstructured
在处理机器学习或大语言模型(LLM)任务时,我们常遇到 PDF、Word、HTML 等非结构化文档。unstructured 是一个 Python 开源库,专门用于将这些复杂文档拆分为标题、段落、列表、表格等结构化元素,并转换为 JSON 格式,方便下游 RAG 系统或模型训练使用。
它采用模块化设计(称为'bricks'),支持分区、清理和格式化,覆盖 25+ 种文件格式,包括 TXT、PDF、DOCX、PPTX、HTML、图片等。核心库开源(Apache 2 许可证),同时也提供 Serverless API 供生产环境使用。
安装与环境配置
基础依赖
首先确保 Python 版本在 3.8 以上(推荐 3.9+)。
pip install unstructured
如果只需要特定格式支持,可以按需安装,例如 DOCX:
pip install "unstructured[docx]"
完整安装包含本地推理依赖(如 PDF 和图片处理):
pip install "unstructured[local-inference]"
系统级依赖
本地处理 PDF 和图片通常需要额外工具,这一步最容易踩坑:
- Tesseract:用于 OCR 识别。Mac 用户可用
brew install tesseract,Linux 需自行编译或安装包管理器版本。 - Poppler:用于 PDF 解析。参考
pdf2image文档安装。 - Pandoc:处理 EPUB、RTF 等格式,建议版本 2.14.2+。
- libmagic:文件类型检测。Mac 用
brew install libmagic,Ubuntu 用sudo apt-get install libmagic1。
验证安装是否成功:
import unstructured
print(unstructured.__version__)
# 示例输出:0.16.17
若使用 Serverless API,需单独安装客户端:
pip install unstructured-client
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 的核心流程是:分区(Partitioning)→ 清理(Cleaning)→ 格式化(Staging)。
1. 分区:将文档拆解为元素
partition 函数会自动检测文件类型并调用对应的解析器。返回的是 Element 对象列表,包含类别(如 Title、NarrativeText)和文本内容。
from unstructured.partition.auto partition
elements = partition(filename=)
element elements[:]:
()

