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

101 lines
4.3 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import logging
from multiprocessing.spawn import old_main_modules
from docx.oxml.ns import qn
from docx.shared import Pt
# 获取日志记录器
logger = logging.getLogger(__name__)
#excluded_list = ['{{year}}','{{month}}', '{{day}}']
# 将文档中的字符串变量替换成提取内容
"""
def replace_text_in_paragraph(paragraph, old_text, new_text):
try:
runs = list(paragraph.runs) # 先复制一份,避免边遍历边修改
for run in runs:
if old_text in run.text:
# 1. 拆分 run把 old_text 前后拆开
before, old, after = run.text.partition(old_text)
run.clear()
paragraph.add_run(before)
target_run = paragraph.add_run(new_text)
paragraph.add_run(after)
# 3. 仅给目标 run 加粗 + 字体
if old_text == "{{sentiment_trend}}":
target_run.bold = True
target_run.font.name = "Times New Roman"
target_run._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
target_run.font.size = Pt(16)
elif old_text.startswith('{{') and old_text.endswith('}}'):
# 其它模板只改字体、字号,不加粗
target_run.font.name = "Times New Roman"
target_run._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
target_run.font.size = Pt(16)
except Exception as e:
logger.exception(f"替换段落里的文本失败:{e}")
print(f"替换段落里的文本失败:{e}")
"""
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 =="{{sentiment_trend}}":
print("定制化加粗")
if old_text in run.text:
before, old, after = run.text.partition(old_text)
run.clear()
paragraph.add_run(before)
target_run = paragraph.add_run(new_text)
paragraph.add_run(after)
before.font.name = "Times New Roman"
before._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
before.font.size = Pt(16)
if old_text == "{{sentiment_trend}}":
target_run.bold = True
target_run.font.name = "Times New Roman"
target_run._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
target_run.font.size = Pt(16)
else:
"""
if old_text in run.text:
run.text = run.text.replace(old_text, new_text)
if old_text.startswith('{{') :
run.font.name = "Times New Roman"
#run.font.name = "仿宋"
run._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
run.font.size = Pt(16)
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}")