如何使用python-docx在Word文档中查找和替换单词/文本

4
例如: 请在一个word文档中找到以下段落。这些段落在一个表格内。
1. 好的,伙计们,请起床。 2. 好的,伙计们,请起身。
我想用“wake”替换“get”。 我只想在第一段中用“wake”替换“get”。 但是,在下面给出的代码中,“get”被替换成“wake”,如下所示。 对于word文档中的所有段落,这种行为都相同。 请按照上述要求提出建议。
实际结果: 1. 好的,伙计们,请醒来。 2. 好的,伙计们,请醒起。
doc = docx.Document("path/docss.docx")
def Search_replace_text():
 for table in doc.tables:
  for row in table.rows:
   for cell in row.cells:
    for paragraph in cell.paragraphs:
     for run in paragraph.runs:
       if str(word.get()) in run.text:
         text = run.text.split(str(word.get())) # Gets input from GUI
         if text[1] == " ":
            run.text = text[0] + str(replace.get()) # Gets input from GUI
            print(run.text)
        else:
            run.text = text[0] + str(replace.get()) + text[1]
     else: break
     doc.save("docss.docx")

我希望得到如下所示的结果:

  1. 各位,醒醒吧。

  2. 各位,起床了。

实际结果:

  1. 各位,醒醒吧。

  2. 各位,正在醒来。


正则表达式比简单的字符串替换更加有效。https://www.w3schools.com/python/python_regex.asp 尤其是,我认为单词边界("\b")在这种情况下会非常有用。 - Shane
2个回答

5
替换文本的问题在于,文本可能会分成多个运行部分,这意味着简单查找和替换文本将不总是起作用。
将我的答案适应于Python docx Replace string in paragraph while keeping style
要替换的文本可能会分成几个运行部分,因此需要进行部分匹配搜索,确定哪些运行部分需要替换文本,然后替换这些被识别的文本。
此函数替换字符串并保留原始文本样式。无论是否需要保留样式,该过程都相同,因为样式可能导致文本被分成多个运行部分,即使文本在视觉上缺乏样式。
代码如下:
import docx


def docx_find_replace_text(doc, search_text, replace_text):
    paragraphs = list(doc.paragraphs)
    for t in doc.tables:
        for row in t.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    paragraphs.append(paragraph)
    for p in paragraphs:
        if search_text in p.text:
            inline = p.runs
            # Replace strings and retain the same style.
            # The text to be replaced can be split over several runs so
            # search through, identify which runs need to have text replaced
            # then replace the text in those identified
            started = False
            search_index = 0
            # found_runs is a list of (inline index, index of match, length of match)
            found_runs = list()
            found_all = False
            replace_done = False
            for i in range(len(inline)):

                # case 1: found in single run so short circuit the replace
                if search_text in inline[i].text and not started:
                    found_runs.append((i, inline[i].text.find(search_text), len(search_text)))
                    text = inline[i].text.replace(search_text, str(replace_text))
                    inline[i].text = text
                    replace_done = True
                    found_all = True
                    break

                if search_text[search_index] not in inline[i].text and not started:
                    # keep looking ...
                    continue

                # case 2: search for partial text, find first run
                if search_text[search_index] in inline[i].text and inline[i].text[-1] in search_text and not started:
                    # check sequence
                    start_index = inline[i].text.find(search_text[search_index])
                    check_length = len(inline[i].text)
                    for text_index in range(start_index, check_length):
                        if inline[i].text[text_index] != search_text[search_index]:
                            # no match so must be false positive
                            break
                    if search_index == 0:
                        started = True
                    chars_found = check_length - start_index
                    search_index += chars_found
                    found_runs.append((i, start_index, chars_found))
                    if search_index != len(search_text):
                        continue
                    else:
                        # found all chars in search_text
                        found_all = True
                        break

                # case 2: search for partial text, find subsequent run
                if search_text[search_index] in inline[i].text and started and not found_all:
                    # check sequence
                    chars_found = 0
                    check_length = len(inline[i].text)
                    for text_index in range(0, check_length):
                        if inline[i].text[text_index] == search_text[search_index]:
                            search_index += 1
                            chars_found += 1
                        else:
                            break
                    # no match so must be end
                    found_runs.append((i, 0, chars_found))
                    if search_index == len(search_text):
                        found_all = True
                        break

            if found_all and not replace_done:
                for i, item in enumerate(found_runs):
                    index, start, length = [t for t in item]
                    if i == 0:
                        text = inline[index].text.replace(inline[index].text[start:start + length], str(replace_text))
                        inline[index].text = text
                    else:
                        text = inline[index].text.replace(inline[index].text[start:start + length], '')
                        inline[index].text = text
            # print(p.text)


# sample usage as per example 

doc = docx.Document('find_replace_test_document.docx')
docx_find_replace_text(doc, 'Testing1', 'Test ')
docx_find_replace_text(doc, 'Testing2', 'Test ')
docx_find_replace_text(doc, 'rest', 'TEST')
doc.save('find_replace_test_result.docx')

样例输出

以下是一些屏幕截图,展示了源文件和替换文本后的结果:

'Testing1' -> 'Test '
'Testing2' -> 'Test '
'rest' -> 'TEST'

源文件:

Source document

结果文档:

Resultant document

我希望这能帮助到某人。


谢谢,我搜寻了很多答案,但只有这个有效!!!而且,是的,运行可能会分成许多部分。 - Ricky Wu

1
替换
if str(word.get()) in run.text:

有点格式

if ' {} '.format(str(word.get())) in run.text:

搜索分隔的单词(使用两个空格)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接