You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
report_app/app/tools/replace_text.py

46 lines
1.6 KiB
Python

import logging
# 获取日志记录器
logger = logging.getLogger(__name__)
# 将文档中的字符串变量替换成提取内容
def replace_text_in_paragraph(paragraph, old_text, new_text):
try:
if old_text in paragraph.text: # 检查段落中是否存在模板字符串
# 遍历段落的每个运行
for run in paragraph.runs:
if old_text in run.text:
run.text = run.text.replace(old_text, new_text)
except Exception as e:
logger.exception(f"替换段落里的文本失败:{e}")
print(f"替换段落里的文本失败:{e}")
def replace_text_in_docx(doc, replacements):
try:
logger.info("开始替换段落中的文本")
# 替换段落中的文本
for paragraph in doc.paragraphs:
for old_text, new_text in replacements.items():
replace_text_in_paragraph(paragraph, old_text, new_text)
except Exception as e:
logger.exception(f"替换段落中的文本失败:{e}")
print(f"替换段落中的文本失败:{e}")
try:
logger.info("开始替换表格中的文本")
# 替换表格中的文本
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for old_text, new_text in replacements.items():
if old_text in cell.text:
cell.text = cell.text.replace(old_text, new_text)
except Exception as e:
logger.exception(f"替换表格中的文本失败:{e}")
print(f"替换表格中的文本失败:{e}")