RandallCloud
RandallCloud

Reputation: 133

How to bold a modified paragraph in python docx

I built a script who modify some word in a imported word file .

from docx import Document

document = Document('filename.docx')

paragraphs = document.paragraphs

dic = {'XxwordxX': modifiedword}

for p in document.paragraphs:
    for key in dic.keys():
        if key in p.text:
            p.text = p.text.replace(key,dic[key])

document.save('new.docx')

Unfortunately, the paragraph where the word has be modified isn't bold anymore (it was bold in filename).

And I cannot found how to bold it again.

I tried this :

from docx import Document

document = Document('filename.docx')

paragraphs = document.paragraphs

dic = {'XxwordxX': modifiedword}

for p in document.paragraphs:
    for key in dic.keys():
        if key in p.text:
            p.text = p.text.replace(key,dic[key])

para = document.paragraphs[2] 
run.bold = True

document.save('new.docx')

But even though I haven't any error, the paragraph isn't bold in the output.

Any ideas how to do that ? The only tips I found on internet are for bold paragraph added manually.

Upvotes: 2

Views: 275

Answers (1)

scanny
scanny

Reputation: 28863

I think you're looking for a solution like the paragraph_replace_text() function here:
https://github.com/python-openxml/python-docx/issues/30#issuecomment-879593691

The problem is that replacing Paragraph.text removes all the runs in the paragraph and replaces them with a single paragraph with default formatting. That's often convenient, but not sufficient in the "replace text while preserving formatting" case.

The documentation on that code snippet is pretty thorough and the comment following that one provides some further explanation. You may need to tweak the paragraph_replace_text() function to suit your use case, so best to study it closely enough to understand basically how it works.

Upvotes: 2

Related Questions