0

I have a docx file such as on the image, img, and I need to replace a word, while keep all the other styles in the paragraph, such as bold and italic text, and make the replaced word bold. So I decided to just do this

    document = Document('minimal.docx')
    for paragraph in document.paragraphs:
        for run in paragraph.runs:
            if "REPLACE" in run.text:
                run.text = run.text.replace("REPLACE", "your own")

but it does not work because assigning to run.text will rebuild all the runs to 1, so the styles will be erased

So I thougth it'd be a good idea to find the run with the needed text, split it in multiple runs and bold the text.

def make_word_bold(paragraph: docx.text.paragraph.Paragraph, word: str):
    for idx, run in enumerate(paragraph.runs):
        if word in run.text:
            before, actual, after = paragraph.runs[:idx], paragraph.runs[idx], paragraph.runs[idx + 1:]

            start, end = run.text.split(word)
            paragraph.add_run(start)
            paragraph.add_run(word).bold = True
            paragraph.add_run(end)
   --->     paragraph.runs = [*before, paragraph.runs[-3], paragraph.runs[-2], paragraph.runs[-1], actual, *after]
            break

The problem here is there is no setter for runs. Any other ideas how can I find and replace a word and apply styles for it?

Ivan
  • 316
  • 3
  • 15
  • Probably duplicate of https://stackoverflow.com/questions/34779724/python-docx-replace-string-in-paragraph-while-keeping-style?rq=2 – Ivan Aug 06 '23 at 11:52

0 Answers0