例如:请在word文档中查找以下段落。这些段落位于表格内。
我正在尝试用“唤醒”代替“获取”。我正在寻找仅在第 1 段的情况下用“wake”替换“get”。但在下面给出的代码中,它在两个段落中都被替换,如下面的结果所示。此行为对于 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")
Run Code Online (Sandbox Code Playgroud)
我想要的结果如下图所示:
好吧,伙计们,请醒来。
好的,请起床。
实际结果: …