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
相关推荐
小墨宝1 天前
web前端学习 langchain
前端·学习·langchain
脚踏实地的大梦想家2 天前
【LangChain】P10 LangChain 提示词模板深度解析(一):Prompt Template
langchain·prompt
OopsOutOfMemory2 天前
LangChain源码分析(十三)- 运行时与监控
ai·langchain·aigc·ai编程·ai应用
OopsOutOfMemory2 天前
LangChain源码分析(一)- LLM大语言模型
人工智能·语言模型·langchain·aigc
脚踏实地的大梦想家2 天前
【LangChain】P7 对话记忆完全指南:从原理到实战(下)
数据库·langchain
超人在良家-阿启2 天前
LangChain 之 DashScopeEmbeddings下的 embed_query和embed_documents的区别
langchain
许泽宇的技术分享3 天前
重塑Excel的智慧边界:ExcelAgentTemplate架构深度解析与LLM集成最佳实践
langchain·excel插件开发
vv_5014 天前
Langchain+Neo4j+Agent 的结合案例-电商销售
人工智能·langchain·agent·neo4j
脚踏实地的大梦想家4 天前
【LangChain】P4 LangChain 多轮对话与上下文记忆深度解析
langchain
一语雨在生无可恋敲代码~5 天前
RAG Day05 混合检索
langchain