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
相关推荐
兆。11 小时前
Agent_RAG_智能食谱推荐系统
langchain·智能体
小刘|18 小时前
揭秘RAG:检索增强生成技术解析
langchain·rag
菜到离谱但坚持20 小时前
【小白零基础】RAG+LangChain 搭建私有知识库问答系统(完整可运行代码+超详细教程+避坑指南)
python·langchain·rag
YsyaaabB21 小时前
LangChain作业二---多语言翻译Prompt
开发语言·python·langchain
兆。1 天前
简历高光_Agent_RAG项目描述
人工智能·langchain
leikooo1 天前
LangChain4j 调用 DeepSeek 工具时报 400?用 pi 抓包定位,同包覆盖修复 reasoning_content
langchain·deepseek
wuhen_n1 天前
RAG 入门:检索增强生成核心原理
前端·人工智能·typescript·langchain·ai编程
晚笙coding1 天前
从零讲透 LangChain 提示词模板:不只是 Prompt,而是“可复用的 AI 指令工厂”
人工智能·langchain·prompt
晚笙coding1 天前
从零讲透 LangChain 输出格式化:让模型真的“能用”
java·开发语言·langchain
颜酱1 天前
LangChain 调大模型:模板拼接 + invoke / stream / batch
python·langchain