我有一个 VBA 宏。在那方面,我有
.Find Text = 'Pollution'
.Replacement Text = '^p^pChemical'
Here, '^p^pChemical'
表示将“污染”一词替换为“化学”,并在“海洋”一词之前创建两个空段落。
Before:
After:
您是否注意到“污染”一词已被“化学”取代,并且前面有两个空段落?这就是我想要的Python。
到目前为止我的代码:
import docx
from docx import Document
document = Document('Example.docx')
for Paragraph in document.paragraphs:
if 'Pollution' in paragraph:
replace(Pollution, Chemical)
document.add_paragraph(before('Chemical'))
document.add_paragraph(before('Chemical'))
我想打开一个word文档找到该单词,将其替换为另一个单词,并在替换的单词之前创建两个空段落。
您可以搜索每个段落以找到感兴趣的单词,然后调用insert_paragraph_before添加新元素:
def replace(doc, target, replacement):
for par in list(document.paragraphs):
text = par.text
while (index := text.find(target)) != -1:
par.insert_paragraph_before(text[:index].rstrip())
par.insert_paragraph_before('')
par.text = replacement + text[index + len(target)]
list(doc.paragraphs)
制作列表的副本,以便在插入元素时不会丢失迭代。
根据需要多次调用此函数以替换您拥有的任何单词。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)