簡體   English   中英

如何替換 .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']替換它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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM