Document 组件与文档加载器 - 学习总结
1. Document.py - 文档加载示例
TextLoader
是什么:LangChain 提供的文档加载器,用于读取本地的纯文本文件
有什么用:
- 将 .txt、.md 等文本文件加载为 LangChain 的 Document 对象
- 作为文档处理流程的第一步(加载 → 分割 → 向量化)
参数:
file_path:文件路径encoding:文件编码(中文需用 "utf-8")
返回:List[Document] 对象列表
Document 对象
是什么:LangChain 中的核心数据结构,表示一个文档
有什么用:
- 统一封装文档内容和元数据
- 作为后续文本分割、向量化、检索等流程的数据载体
属性:
page_content:文档的文本内容(字符串)metadata:文档元数据(字典,如 source 文件路径)
代码内容
from langchain_community.document_loaders import TextLoader
import os
# 获取脚本所在目录的绝对路径
script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, "document.txt")
# 创建 TextLoader 加载器
loader = TextLoader(file_path, encoding="utf-8")
# 加载文档
documents = loader.load()
# 打印结果
print(documents) # Document 对象列表
print(len(documents)) # 文档数量
print(documents[0].metadata) # 文档元数据
运行结果
# documents 输出:
[
Document(
page_content='1. 潮汕手工牛肉丸\n产品名称: 潮汕手工牛肉丸\n电商网址: shop.example.com/beefballs\n...',
metadata={'source': 'document.txt'}
)
]
# len(documents) 输出:
1
# documents[0].metadata 输出:
{'source': 'document.txt'}
2. document.txt - 示例文档
文件内容
潮汕手工牛肉丸的产品信息,包含:
- 产品名称、电商网址
- 产品描述
- 产品特点(原材料、制作工艺、口感、净重、保质期等)
- 发货方式、物流信息
- 推荐菜系