我有一个文档要替换多个单词。但是我不能超过一个。这是我的代码:
import re
from docx import Document
def docx_replace_regex(doc_obj: object, regex: object, replace: object) -> object:
for p in doc_obj.paragraphs:
if regex.search(p.text):
inline = p.runs
for i in range(len(inline)):
if regex.search(inline[i].text):
text = regex.sub(replace, inline[i].text)
inline[i].text = text
for table in doc_obj.tables:
for row in table.rows:
for cell in row.cells:
docx_replace_regex(cell, regex , replace)
regex1 = re.compile(r"Question Number 1")
replace1 = r"Q1"
regex2 = re.compile(r"Question Number 2")
replace2 = r"Q2"
regex3 = re.compile(r"Question Number 3")
replace3 = r"Q3"
regex4 = re.compile(r"Question Number 4")
replace4 = r"Q4"
regex5 = re.compile(r"Question Number 5")
replace5 = r"Q5"
filename = "template.docx"
doc = Document(filename)
for i in range(1, 5):
reg = "regex" + str(i)
rep = "replace" + str(i)
docx_replace_regex(doc, reg, rep)
doc.save('result9.docx')
我前一段时间写了这段代码,在不知道如何解决该问题的许多尝试之后我就放弃了。所以我不记得大部分内容,而我仍然坚持如何解决这个问题。