首页 > 解决方案 > How to replace multiple words in .docx file and save the docx file using python-docx

问题描述

I'm trying to change the content of the docx using python-docx library. My changes are about replacing the words. So, I have list of words Original word list: ['ABC','XYZ'] which I need to replace with revised word list: ['PQR', 'DEF']. I also need to preserve the format of these words. Right now, I can save only one change. Here is my code for the reference.

def replace_string(filename='test.docx'):
doc = Document(filename)
list= ['ABC','XYZ']
list2 = ['PQR','DEF']
for p in doc.paragraphs:
        print(p.text)
        for i in range(0, len(list)):
            if list[i] in p.text:
                print('----!!SEARCH FOUND!!------')
                print(list[i])
                print(list2[i])
                print('\n')
                inline = p.runs
                # Loop added to work with runs (strings with same style)
                for i in range(len(inline)):
                    #print(inline[i].text)
                    if list[i] in inline[i].text:
                        print('----SEARCH FOUND!!------')
                        text = inline[i].text.replace(list[i], list2[i])
                        inline[i].text = text
                        print(inline[i].text)
        doc.save('dest1.docx')
return 1

replace_string()

Original content of test.docx file:

ABC XYZ

Revised content or saved content of dest1.docx file:

PQR XYZ

How can I save all the replacements? The list of word may increase and its size is not fix.

标签: pythonpython-docx

解决方案


以下代码对我有用。这也保留了格式。希望这对其他人有帮助。

def replace_string1(filename='test.docx'):
doc = Document(filename)
list= ['ABC','XYZ']
list2 = ['PQR','DEF']
for p in doc.paragraphs:
    inline = p.runs
    for j in range(0,len(inline)):
        for i in range(0, len(list)):
            inline[j].text = inline[j].text.replace(list[i], list2[i])
            print(p.text)
            print(inline[j].text)
doc.save('dest1.docx')
return 1

推荐阅读