在替换python-docx中的单词时保留样式

时间:2018-06-21 08:14:53

标签: python docx python-docx

我写了一个小函数用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,任何可行的解决方案或软件包都可以使用

1 个答案:

答案 0 :(得分:1)

答案已经在this链接中提供。希望这可以帮助。

当您将段落替换为其他文本时,这将保留段落的样式和格式。

相关问题