首先感谢 艾派森 老师的 Python操作word基础 。
我在学习 Word通过模板生成文档 时,发现匹配不上,原因是遍历runs时,文字块run并不是按照标点符号设置的,所以被替换的对象可能会被拆分。我尝试将整个段落paragraph的runs合并成1个run,再进行替换,方案可行。也可以清除runs的内容,将最后一个run替换成修改后的数据。总之,保证在run层面替换就不会丢失样式。
模板如下:
替换后的新文档如下:
代码如下:
# pip install python-docx
from docx import Document
def write2(path_template, path_new, dic_old_new):
# 打开文档
doc1 = Document(path_template)
# 读取里面的数据
for p in doc1.paragraphs:
# 先获取本段的文字,存入变量t
t = p.text
# 替换数据,注意不是直接替换段落的数据,而是替换变量t中的数据。
replace = False
for old, new in dic_old_new.items():
if old in t:
replace = True
t = t.replace(old, new)
if replace is False:
continue
# 将runs内容删除,将最后一个run替换成修改后的数据.
for i, run in enumerate(p.runs):
run.text = ''
if i == len(p.runs) - 1:
run.text = t
# 保存新文件
doc1.save(path_new)
dic_old_new = {'{0}': '00001', '{1}': '2030', '{2}': '01', '{3}': '01', '{4}': '01', '{5}': '01', '{6}': '闯红灯', '{7}': '600'}
write2('template.docx', 'new.docx', dic_old_new)