-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.py
More file actions
99 lines (71 loc) · 3.59 KB
/
Copy pathinsert.py
File metadata and controls
99 lines (71 loc) · 3.59 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import re
import os
from docx import Document
from dotenv import load_dotenv
# 加载 .env 文件中的环境变量
load_dotenv()
def insert_identifiers_in_text(text):
# 正则表达式:匹配任务编号和任务内容
pattern = re.compile(r'(\d+、)(.*?)(?=\d+、|$)', re.DOTALL)
# 匹配所有任务
tasks = pattern.findall(text)
# 用于存储带标识的任务
updated_tasks = []
# 遍历所有任务并插入标识
for i, task in enumerate(tasks, 1):
task_number = int(task[0].strip('、'))
task_content = task[1].strip()
# 初始化 task_content_with_images 为 task_content
task_content_with_images = task_content
# 插入 SQL 和图像标识
task_content_with_sql = task_content_with_images.replace("(文本):",
f"(文本):\n[{task_number-1}-sql]")
# 处理“查看执行结果”并添加图像标识
task_content_with_images = task_content_with_sql.replace("(2)查看视图内容:",
f"(2)查看视图内容:\n[{task_number-1}-img-before]\n[{task_number-1}-img-after]")
# 处理“查看执行结果”,添加img标识
task_content_with_images = task_content_with_images.replace("查看执行结果",
f"查看执行结果\n[{task_number-1}-img-before]\n[{task_number-1}-img-after]")
# 处理“执行操作前基本表数据:”并插入图像标识
task_content_with_images = task_content_with_images.replace("执行操作前基本表数据:",
f"执行操作前基本表数据:\n[{task_number-1}-img-before]")
# 处理“执行操作后基本表数据:”并插入图像标识
task_content_with_images = task_content_with_images.replace("执行操作后基本表数据:",
f"执行操作后基本表数据:\n[{task_number-1}-img-after]")
# 将更新后的任务内容添加到列表
updated_tasks.append(f"{task_number}、{task_content_with_images}")
# 将更新后的任务内容合并为最终文本
return "\n\n".join(updated_tasks)
def read_word_file(file_path):
"""读取 Word 文件并返回文本内容"""
doc = Document(file_path)
full_text = []
for para in doc.paragraphs:
full_text.append(para.text)
return "\n".join(full_text)
def save_to_word(updated_text, output_path):
# print(repr(updated_text))
# 将更新后的文本保存为新的 Word 文件
doc = Document()
# 先将更新后的文本分割为每个段落
paragraphs = updated_text.split('\n')
# 遍历每个段落,将其添加到 Word 中
for para in paragraphs:
# 将每个段落的换行符替换为段落标记
doc.add_paragraph(para)
doc.save(output_path)
# 从环境变量中获取文件路径
file_path = os.getenv("FILE_PATH", "")
# 打印文件路径,确保它正确读取
print(f"读取的文件路径: {file_path}")
# 确保文件路径有效
if not file_path:
print("未找到文件路径,请检查 .env 文件中的配置")
else:
original_text = read_word_file(file_path)
# 调用函数插入标识
updated_text = insert_identifiers_in_text(original_text)
# 打印更新后的文本(可选)
# print(updated_text)
# 保存到新的 Word 文件
save_to_word(updated_text, "./insert_test3.docx")