langchain 加载各种格式文件读取方法

参考:https://python.langchain.com/docs/modules/data_connection/document_loaders/

https://github.com/thomas-yanxin/LangChain-ChatGLM-Webui/blob/master/app.py

1、代码

可以支持pdf、md、doc、txt、csv等格式

复制代码
from langchain.document_loaders import UnstructuredFileLoader
import re
from typing import List

from langchain.text_splitter import CharacterTextSplitter


class ChineseTextSplitter(CharacterTextSplitter):
    def __init__(self, pdf: bool = False, **kwargs):
        super().__init__(**kwargs)
        self.pdf = pdf

    def split_text(self, text: str) -> List[str]:
        if self.pdf:
            text = re.sub(r"\n{3,}", "\n", text)
            text = re.sub('\s', ' ', text)
            text = text.replace("\n\n", "")
        sent_sep_pattern = re.compile(
            '([﹒﹔﹖﹗.。!?]["'"」』]{0,2}|(?=["'"「『]{1,2}|$))') 
        sent_list = []
        for ele in sent_sep_pattern.split(text):
            if sent_sep_pattern.match(ele) and sent_list:
                sent_list[-1] += ele
            elif ele:
                sent_list.append(ele)
        return sent_list



def load_file(filepath):
    if filepath.lower().endswith(".md"):
        loader = UnstructuredFileLoader(filepath, mode="elements")
        docs = loader.load()
    elif filepath.lower().endswith(".pdf"):
        loader = UnstructuredFileLoader(filepath)
        textsplitter = ChineseTextSplitter(pdf=True)
        docs = loader.load_and_split(textsplitter)
    else:
        loader = UnstructuredFileLoader(filepath, mode="elements")
        textsplitter = ChineseTextSplitter(pdf=False)
        docs = loader.load_and_split(text_splitter=textsplitter)
    return docs

继续把上面切分数据保存到FAISS

参考:https://blog.csdn.net/weixin_42357472/article/details/133778618?spm=1001.2014.3001.5502

复制代码
from langchain.vectorstores import FAISS
from langchain.embeddings import HuggingFaceEmbeddings

embedding = HuggingFaceEmbeddings(model_name=r"C:\Users\loong\.cache\huggingface\hub\models--shibing624--text2vec-base-chinese\snapshots\2642****1812248")  ##HuggingFace离线模型,用加载HuggingFaceEmbeddings

##保存向量
docs = load_file(r"C:\Users\loong\D***资料.txt")
vector_store = FAISS.from_documents(docs, embedding)
vector_store.save_local('faiss_index')

## query 向量库搜索测试

query = "公司地址"
vector_store.similarity_search(query)

2、另外单独加载pdf,制定chunk_size,不是特定上面中文安装标点分

复制代码
from langchain.document_loaders import UnstructuredFileLoader


loader = UnstructuredFileLoader(r"C:\Use***\数字人研究报告.pdf")
textsplitter = CharacterTextSplitter(
    chunk_size=200,
    chunk_overlap=20)
chunks = loader.load_and_split(textsplitter)
for num,chunk in enumerate(chunks):
    print(num,chunk)

loader.load()单独获取UnstructuredFileLoader里全部数据

复制代码
loader = UnstructuredFileLoader(r"C:\Use***\数字人研究报告.pdf")
data =loader.load()[0].page_content
data
相关推荐
小王努力学编程几秒前
LangChain——AI应用开发框架(核心组件2)
linux·服务器·c++·人工智能·python·langchain·信号
小雨青年9 分钟前
环境准备 Windows Mac 下 Docker Desktop 的安装与镜像源加速
windows·macos·docker
高洁0112 分钟前
数字孪生应用于特种设备领域的技术难点
人工智能·python·深度学习·机器学习·知识图谱
Piar1231sdafa19 分钟前
基于YOLOv26的海洋鱼类识别与检测系统深度学习训练数据集Python实现_1
python·深度学习·yolo
不会代码的小测试21 分钟前
页面动态元素无法快速复制定位解决
python·selenium·自动化
easyboot26 分钟前
C#使用pythonnet简单示例
开发语言·python·c#
小二·40 分钟前
Python Web 开发进阶实战:AI 智能体操作系统 —— 在 Flask + Vue 中构建多智能体协作与自主决策平台
前端·人工智能·python
GatiArt雷43 分钟前
AI 赋能 Python:基于 LLM + Pandas 的自动化数据清洗实操AI赋能Python数据清洗:基于LLM+Pandas的自动化实操
人工智能·langchain
计算机徐师兄1 小时前
Python基于Django的图片推荐系统(附源码,文档说明)
python·django·网络爬虫·图片推荐系统·python图片推荐系统·python图片推荐·图片推荐
数据知道1 小时前
一文掌握 MongoDB 详细安装与配置(Windows / Linux / macOS 全平台)
linux·数据库·windows·mongodb·macos