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
相关推荐
花千树-0103 小时前
Proposer-Critic 多轮辩论:两个 LLM Agent 用 loop() 逼近共识
langchain·agent·ai编程·skill·multi-agent·claude code·ai 工程化
Daydream.V5 小时前
从零搭建 AI Agent:LLM Agent+Function Calling+Dify 本地部署 + Coze 实战全攻略
人工智能·langchain·ollama·functioncalling·大模型部署
JaydenAI6 小时前
[Deep Agents:LangChain的Agent Harness-06]通过HumanInTheLoopMiddleware引入人机交互
langchain·人机交互·hitl·deep agents·harness
H_unique8 小时前
LangChain:提示词模板
ai·langchain
Zfox_9 小时前
【LangGraph】持久化(Persistence)
开发语言·人工智能·redis·langchain·ai编程·langgraph
Allnadyy18 小时前
【LangChain&LangGraph】LangChain与LangGraph介绍
langchain
qq_283720051 天前
LangChain+FAISS 向量数据库搭建轻量化 RAG 应用
数据库·langchain·faiss
情绪总是阴雨天~1 天前
LangChain 核心技术全解析:从入门到实战
langchain
H_unique1 天前
LangChain:消息
开发语言·langchain
JaydenAI1 天前
[Deep Agents:LangChain的Agent Harness-12]利用create_deep_agent整合所有的Harness中间件
langchain·agent·deep agents·harness