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
相关推荐
shut up13 小时前
LangChain - 如何使用阿里云百炼平台的Qwen-plus模型构建一个桌面文件查询AI助手 - 超详细
人工智能·python·langchain·智能体
liliangcsdn13 小时前
如何基于ElasticsearchRetriever构建RAG系统
大数据·elasticsearch·langchain
东方佑14 小时前
基于FastAPI与LangChain的Excel智能数据分析API开发实践
langchain·excel·fastapi
大模型教程2 天前
搞懂 LangChain RAG:检索、召回原理及 docid 的关键意义
程序员·langchain·llm
AI大模型2 天前
别再死磕 Chain 了!想做复杂的 Agent,你必须得上 LangGraph
程序员·langchain·llm
玲小珑2 天前
LangChain.js 完全开发手册(十四)生产环境部署与 DevOps 实践
前端·langchain·ai编程
weixin_438077493 天前
langchain官网翻译:Build a Question/Answering system over SQL data
数据库·sql·langchain·agent·langgraph
老顾聊技术3 天前
【AI课程上线了哦,打造类FastGPT产品】
langchain·rag
行者阿毅3 天前
langchain4j+SpringBoot+DashScope(灵积)整合
spring boot·langchain·ai编程
深度学习机器3 天前
AI Agent上下文工程设计指南|附实用工具推荐
langchain·llm·agent