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
相关推荐
AI大模型2 小时前
构建可调用外部工具的AI助手:LangChain函数调用与API集成详解
程序员·langchain·llm
小陈phd6 小时前
langchain从入门到精通(七)——利用回调功能调试链应用 - 让过程更透明
android·java·langchain
thinking-fish1 天前
提示词Prompts(2)
python·langchain·提示词·提示词模板
Python测试之道2 天前
RAG实战:基于LangChain的《肖申克的救赎》知识问答系统构建指南
langchain·embedding·rag·deepseek
MarkGosling2 天前
🚀 引言:当 Java 遇上大模型,LangChain 4 j 如何成为开发者的「AI 胶水」?
java·langchain
用户711283928473 天前
什么?大模型删库跑路了?
langchain·llm
金汐脉动3 天前
LangChain × Elasticsearch:手把手教你搭建智能向量数据库
langchain
金汐脉动3 天前
LangChain × PGVector:手把手教你搭建智能向量数据库
langchain
耿玉3 天前
什么是 AI AGENT?与大语言模型的区别?
langchain·ai编程
AI大模型学习教程4 天前
前端学AI之LangChain.js入门教程:实现智能对话机器人
人工智能·langchain