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 小时前
LangChain1.0速通指南(二)——LangChain1.0 create_agent api 基础知识
人工智能·langchain·mcp
FreeCode13 小时前
LangChain1.0智能体开发:模型使用
人工智能·langchain·agent
chenchihwen19 小时前
AI代码开发宝库系列:LangChain 工具链:从LCEL到实际应用
人工智能·python·langchain·rag
扯蛋4381 天前
LangChain的学习之路( 一 )
前端·langchain·mcp
serve the people2 天前
Formatting Outputs for ChatPrompt Templates(one)
langchain·prompt
serve the people2 天前
LangChain Few-Shot Prompt Templates(two)
langchain·prompt
IvanCodes3 天前
一、初识 LangChain:架构、应用与开发环境部署
人工智能·语言模型·langchain·llm
serve the people3 天前
MessagePromptTemplate Types in LangChain
langchain
chenchihwen3 天前
AI代码开发宝库系列:Text2SQL深度解析基于LangChain构建
人工智能·python·langchain·text2sql·rag
二向箔reverse3 天前
用langchain搭建简单agent
人工智能·python·langchain