Langchain 对pdf,word,txt等不同文件的加载解析

项目中遇到各种数据资源想要加载近langchain构建本地知识ai系统,怎么加载对应的文件格式呢,一起研究下

引入Langchain

复制代码
from langchain.document_loaders import UnstructuredWordDocumentLoader,PyPDFium2Loader,DirectoryLoader,PyPDFLoader,TextLoader
import os

pdf文件加载

复制代码
def load_pdf(directory_path):
    data = []
    for filename in os.listdir(directory_path):
        if filename.endswith(".pdf"):
            print(filename)
            # print the file name
            loader = PyPDFium2Loader(f'{directory_path}/{filename}')
            print(loader)
            data.append(loader.load())
    return data

word文档加载如,doc或者docx格式

复制代码
def load_word(directory_path):
    data = []
    for filename in os.listdir(directory_path):
        # check if the file is a doc or docx file
        # 检查所有doc以及docx后缀的文件
        if filename.endswith(".doc") or filename.endswith(".docx"):
            # langchain自带功能,加载word文档
            loader = UnstructuredWordDocumentLoader(f'{directory_path}/{filename}')
            data.append(loader.load())

    return data

txt加载

复制代码
def load_txt(directory_path):
    data = []
    for filename in os.listdir(directory_path):
        if filename.endswith(".txt"):
            print(filename)
            loader = TextLoader(f'{directory_path}/{filename}')
            print(loader)
            data.append(loader.load())

    return data

上述中常见的文档格式基本上都可以加载进去了,主要就是不同格式对应不同的加载方式,如果想简单也可以直接加载目录

复制代码
def load_docs(directory):
    loader = DirectoryLoader(directory)
    documents = loader.load()
    return documents
相关推荐
hryou09228 小时前
做AI-Agent总查不准还运维崩溃2026向量数据库避坑指南
langchain·ai编程·aiops
富贵儿9983 天前
NL2SQL 实践手记 04:多表查询为什么更难——让模型找对表、连对关系
数据库·sql·ai·自然语言处理·langchain
budingxiaomoli3 天前
LangChain与LangGraph介绍
人工智能·langchain
tong_li4 天前
给娃做个 AI 陪写作业助手:LangChain4j 入门(九):AI 分得清老大和老二(多用户隔离与 token 认证)
后端·langchain
东东吖5 天前
07-LangChain Agent智能助手构建笔记
langchain·llm·agent
deep_long5 天前
03|MCP 接入 LangChain Agent:stdio 与 Streamable HTTP 实战
langchain·mcp·mcp生产实践
东东吖5 天前
06-LangChain 结构化输出学习笔记
langchain·llm·agent
东东吖5 天前
04-LangChain Message 与提示词模板学习笔记
langchain·llm·agent
东东吖5 天前
03-LangSmith 使用学习笔记
langchain·llm·agent
东东吖5 天前
05-LangChain Tool 学习笔记
langchain·llm·agent