1

I've written a small function to replace certain words with python-docx, which works great except that it changes some style element but weirdly not all of them.

My function (simplified):

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)

This works for replacing words or sentences, but fails to preserve some style elements for the paragraph (alignment, font size, bold) but preserves others (double underline for example). So my question:

Is there a better way to replace phrases in docx files, while still keeping all of the former styling?

Note: i'm not "married" to python-docx, any solution or package that works will do

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62

1 Answers1

1

The answer is already provided in this link. Hope this helps.

This will retain the style and formatting for a paragraph when you replace it with some other text.

Community
  • 1
  • 1
Khusbu Mishra
  • 161
  • 4
  • 13