我编写了一个小函数来用 python-docx
替换某些单词,它效果很好,只是它改变了一些样式元素,但奇怪的是不是全部。
我的功能(简化):
def template2doc(replace_dict, source, destination):
"""
Creates a new docx file from a template, replacing keywords withing the template and saving with a new name
:param replace_dict: dict for replacing each key with its value
:param source: path to source template file
:param destination: path to save the result document
:return: None
"""
doc = docx.Document(source)
for key, replacement in replace_dict.items():
for paragraph in doc.paragraphs:
if key in par.text:
paragraph.text = paragraph.text.replace(key, replacement)
# Save the result
doc.save(destination)
这适用于替换单词或句子,但无法保留段落的某些样式元素(对齐、字体大小、粗体),但保留其他元素(例如双下划线)。所以我的问题是:
是否有更好的方法来替换 docx 文件中的短语,同时仍保留所有以前的样式?
注意:我没有“嫁给”python-docx
,任何有效的解决方案或包都可以
最佳答案
答案已在 this 中提供关联。希望这会有所帮助。
当您将段落替换为其他文本时,这将保留段落的样式和格式。
关于python - 在替换 python-docx 中的单词时保留样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50963613/