Python docx Replace string in paragraph while keeping style

前端 未结 3 1508
终归单人心
终归单人心 2020-12-01 07:16

I need help replacing a string in a word document while keeping the formatting of the entire document.

I\'m using python-docx, after reading the documentation, it wo

3条回答
  •  天涯浪人
    2020-12-01 07:39

    I posted this question (even though I saw a few identical ones on here), because none of those (to my knowledge) solved the issue. There was one using a oodocx library, which I tried, but did not work. So I found a workaround.

    The code is very similar, but the logic is: when I find the paragraph that contains the string I wish to replace, add another loop using runs. (this will only work if the string I wish to replace has the same formatting).

    def replace_string(filename):
        doc = Document(filename)
        for p in doc.paragraphs:
            if 'old text' in p.text:
                inline = p.runs
                # Loop added to work with runs (strings with same style)
                for i in range(len(inline)):
                    if 'old text' in inline[i].text:
                        text = inline[i].text.replace('old text', 'new text')
                        inline[i].text = text
                print p.text
    
        doc.save('dest1.docx')
        return 1
    

提交回复
热议问题