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
相关推荐
go4it5 小时前
聊聊langchain4j的AiServices
langchain
王毕业1 天前
从零开始解析RAG(二):路由与查询构建——让数据主动响应问题
langchain
雪语.2 天前
AI大模型学习(五): LangChain(四)
数据库·学习·langchain
ILUUSION_S2 天前
结合RetrievalQA和agent的助手
python·学习·langchain
王毕业3 天前
从零解析RAG(一)
langchain
neoooo4 天前
LangChain与Ollama构建本地RAG知识库
人工智能·langchain·aigc
charles_vaez4 天前
开源模型应用落地-LangGraph101-探索 LangGraph人机交互-添加断点(一)
深度学习·自然语言处理·langchain
牛奶4 天前
前端学AI:LangChain、LangGraph和LangSmith的核心区别及定位
前端·langchain·ai 编程
牛奶4 天前
前端学AI:基于Node.js的Langchain开发-简单实战应用
前端·langchain·node.js
星星点点洲5 天前
【LangChain.js】Python版LangChain 的姊妹项目
javascript·langchain