How to use python-docx to replace text in a Word document and save

后端 未结 7 1912
后悔当初
后悔当初 2020-11-29 19:25

The oodocx module mentioned in the same page refers the user to an /examples folder that does not seem to be there.
I have read the documentation of python-docx 0.7.2, p

相关标签:
7条回答
  • 2020-11-29 20:15

    I got much help from answers from the earlier, but for me, the below code functions as the simple find and replace function in word would do. Hope this helps.

    #!pip install python-docx
    #start from here if python-docx is installed
    from docx import Document
    #open the document
    doc=Document('./test.docx')
    Dictionary = {"sea": "ocean", "find_this_text":"new_text"}
    for i in Dictionary:
        for p in doc.paragraphs:
            if p.text.find(i)>=0:
                p.text=p.text.replace(i,Dictionary[i])
    #save changed document
    doc.save('./test.docx')
    

    The above solution has limitations. 1) The paragraph containing The "find_this_text" will became plain text without any format, 2) context controls that are in the same paragraph with the "find_this_text" will be deleted, and 3) the "find_this_text" in either context controls or tables will not be changed.

    0 讨论(0)
提交回复
热议问题