【AI-Snova】数据提取(Data Extraction)--DOCX extraction

写在前面

  • examples of text extraction from DOCX files with different packages

    从具有不同包的 DOCX 文件中提取文本的示例

内容列表

依赖导入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 设置项目目录的路径,并确保需要的模块在 Python 路径中可用,之后导入了用于数据处理和环境管理的一些库

import os # 与操作系统交互
import sys # 对 Python 解释器的访问

current_dir = os.getcwd() # 当前工作目录的路径
kit_dir = os.path.abspath(os.path.join(current_dir, ".."))
repo_dir = os.path.abspath(os.path.join(kit_dir, ".."))
# os.path.abspath 将路径转换为绝对路径
# os.path.join 用于连接目录和文件名,这里 current_dir 的上一级目录("..")被赋值给 kit_dir
# kit_dir 的上一级目录被赋值给 repo_dir



# sys.path 是一个列表,包含了 Python 查找模块的路径
sys.path.append(kit_dir)
sys.path.append(repo_dir)


import glob
import pandas as pd
from dotenv import load_dotenv
from langchain.text_splitter import RecursiveCharacterTextSplitter
from tqdm.autonotebook import trange

# glob 模块用于查找符合特定规则的文件路径名
# pandas 是一个数据分析库,常用作处理数据的工具
# dotenv 模块用于加载环境变量
# RecursiveCharacterTextSplitter 是 langchain 库中的一个文本拆分器,用于处理文本数据
# trange 是 tqdm 库中的一个进度条显示工具,用于在 Jupyter Notebook 中显示进度条

加载DOCX文件的方式

1
2
3
folder_loc = os.path.join(kit_dir,'data/sample_data/sample_files/')  # 指定文件夹路径
docx_files = list(glob.glob(f'{folder_loc}/*.docx')) # 搜索 folder_loc 路径下所有扩展名为 .docx 的文件,返回这些文件的完整路径列表
file_path = docx_files[0] # 取第一个文件的路径

加载分词器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 通过使用 RecursiveCharacterTextSplitter 来创建一个文本分割器,它的目的是将大段的文本拆分为更小的片段,同时保留一定的重叠部分,便于处理和分析长文本

text_splitter = RecursiveCharacterTextSplitter(
# Set a small chunk size, just to make splitting evident.
chunk_size = 200,
chunk_overlap = 20,
length_function = len,
add_start_index = True,
separators = ["\n\n\n","\n\n", "\n", "."]
)


# chunk_size 指定每个分割块的大小(即每个块的字符数)
# chunk_overlap 每个分割块之间的重叠字符数
# length_function 指定用于计算文本长度的函数
# add_start_index 指定了是否添加起始索引
# separators 指定用于分割文本的分隔符
# 文本将在以下情况下被分割:
# 当出现三个连续的换行符 (\n\n\n)
# 当出现两个换行符 (\n\n)
# 一个换行符 (\n)
# 句点(.)

从非结构化本地 DOCX 加载程序加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 加载和拆分 Word 文档中的内容,并将拆分后的文本段落逐一打印出来


# 导入文档加载器
# UnstructuredWordDocumentLoader 是一个专门用于加载非结构化 Word 文档的工具
from langchain.document_loaders import UnstructuredWordDocumentLoader


# 创建文档加载器实例
loader = UnstructuredWordDocumentLoader(file_path, mode="elements")
# 用于加载 file_path 指定的 .docx 文件


# 加载并拆分文档
docs_unstructured_local = loader.load_and_split(text_splitter = text_splitter)
# loader.load_and_split(...) 方法用于加载文档并将其拆分为较小的片段
# text_splitter 文本拆分器
# docs_unstructured_local 是列表,其中每个元素是一个文档片段对象


# 遍历输出
for doc in docs_unstructured_local:
print(f'{doc.page_content}\n---')

从非结构化 io API 加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 使用了 langchain 库中的 UnstructuredAPIFileLoader 类来加载并处理文档

from langchain.document_loaders import UnstructuredAPIFileLoader
# 这个类用于通过 Unstructured API 加载文件,并将其转换为结构化的数据格式
# 提示:需要提前在Unstructured.io注册一个免费API Key
load_dotenv(os.path.join(repo_dir,'.env'))


loader = UnstructuredAPIFileLoader(file_path,
mode="elements",
api_key=os.environ.get('UNSTRUCTURED_API_KEY'),
url=os.environ.get("UNSTRUCTURED_URL"))
# file_path: 需要加载的文件路径
# mode="elements": 指定如何处理文件内容。"elements" 模式会将文件内容拆分为不同的元素(如段落、标题、列表等)
# api_key: 从环境变量中获取的 Unstructured API 密钥
# url: 从环境变量中获取的 Unstructured API 的 URL


# 加载并分割文档
# text_splitter →文本分割器,用于指定如何将文档内容拆分为更小的片段
docs_unstructured_api = loader.load_and_split(text_splitter = text_splitter)


# 打印每个文档片段
for doc in docs_unstructured_api:
print(f'{doc.page_content}\n---')

通过嵌入相似性来评估 loded docs

嵌入和存储

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from langchain.embeddings import HuggingFaceInstructEmbeddings
from langchain.vectorstores import FAISS


# 设置嵌入参数
# True:生成嵌入向量后对其进行归一化处理,有助于提高相似度搜索的准确性
encode_kwargs = {'normalize_embeddings': True}


# 创建嵌入模型
embd_model = HuggingFaceInstructEmbeddings( model_name='intfloat/e5-large-v2',
embed_instruction="", # no instructions needed for candidate passages
query_instruction="Represent this sentence for searching relevant passages: ", encode_kwargs=encode_kwargs
)
# model_name='intfloat/e5-large-v2': 指定使用的 Hugging Face 模型名称。intfloat/e5-large-v2 是一个预训练的嵌入模型,适用于多种自然语言处理任务。
# embed_instruction="": 用于生成候选段落嵌入的指令。这里设置为空字符串,表示不需要额外的指令。
# query_instruction="Represent this sentence for searching relevant passages: ": 用于生成查询嵌入的指令。这个指令告诉模型如何将查询句子转换为嵌入向量,以便搜索相关的段落。
# encode_kwargs=encode_kwargs: 传递给嵌入模型的额外参数,这里设置了嵌入向量的归一化


# 创建本地文档的向量存储
vectorstore_unstructured_local = FAISS.from_documents(documents=docs_unstructured_local, embedding=embd_model)

# 创建API文档的向量存储
vectorstore_unstructured_api = FAISS.from_documents(documents=docs_unstructured_api, embedding=embd_model)

# HuggingFaceInstructEmbeddings: 用于生成文本嵌入的类,基于 Hugging Face 的模型
# FAISS: 用于创建和管理向量存储的类 一个高效的向量相似度搜索库

相似度搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 用于在 VectorStore 中执行相似性搜索
# VectorStore 是一个用于存储和检索向量数据的库

query = "what is the Bankruptcy Reform Act?" # query→要搜索的关键词

ans = vectorstore_unstructured_local.similarity_search(query)
# 在本地加载器中执行相似性搜索,返回一个包含匹配结果的列表
print("-------Unstructured local Loader----------\n")
print(ans[0].page_content)


ans_2 = vectorstore_unstructured_api.similarity_search(query)
# 在API加载器中执行相似性搜索,返回一个包含匹配结果的列表
print("--------Unstructured api loader------------\n")
print(ans_2[0].page_content)
  • Copyrights © 2024-2025 brocademaple
  • 访问人数: | 浏览次数:

      请我喝杯咖啡吧~

      支付宝
      微信