如何替换 .docx 文件中的多个单词并使用 python-docx 保存 docx 文件

How to replace multiple words in .docx file and save the docx file using python-docx

我正在尝试使用 python-docx 库更改 docx 的内容。我的更改是关于替换单词。所以,我有单词列表 Original word list: ['ABC','XYZ'],我需要将其替换为 revised word list: ['PQR', 'DEF']。我还需要保留这些单词的格式。现在,我只能保存一个更改。这是我的参考代码。

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()

test.docx 文件的原始内容:

ABC XYZ

dest1.docx 文件的修改内容或保存内容:

PQR XYZ

如何保存所有的替换?词表可能会增加,大小不固定

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

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

我实现了 JT28 解决方案的一个版本,使用字典替换文本(而不是两个列表)- 这让我可以更简单地生成配对查找、替换项。 Key 是我要查找的内容,而 v 是新子字符串中的内容。该函数允许替换一个段落或所有段落,具体取决于调用者是否迭代(或不迭代)doc.paragraphs。

# NEW FUNCTION:
def replacer(p, replace_dict):
    inline = p.runs  # Specify the list being used
    for j in range(0, len(inline)):

        # Iterate over the dictionary
        for k, v in replace_dict.items():
            if k in inline[j].text:
                inline[j].text = inline[j].text.replace(k, v)
    return p

# Replace Paragraphs
doc = Document(filename)  # Get the file
dict = {'ABC':'PQR', 'XYZ':'DEF'}  # Build the dict
for p in doc.paragraphs:  # If needed, iter over paragraphs
    p = replacer(p, dict)  # Call the new replacer function