我编写了一个小函数,将某些单词替换为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,任何有效的解决方案或包都行
发布于 2018-08-16 02:04:55
答案已经在this链接中提供了。希望这能有所帮助。
这将保留段落的样式和格式,当您将其替换为其他文本时。
https://stackoverflow.com/questions/50963613
复制相似问题