I have a VBA Macro. In that, I have
.Find Text = 'Pollution' .Replacement Text = '^p^pChemical'
Here, '^p^pChemical'
means Replace the Word Pollution with Chemical and create two empty paragraphs before the word sea.
Before:
After:
Have you noticed that The Word Pollution has been replaced With Chemical and two empty paragraphs preceds it ? This is how I want in Python.
My Code so far:
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'))
I want to open a word document to find the word, replace it with another word, and create two empty paragraphs before the replaced word.
Advertisement
Answer
You can search through each paragraph to find the word of interest, and call insert_paragraph_before
to add the new elements:
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)
makes a copy of the list, so that the iteration is not thrown off when you insert elements.
Call this function as many times as you need to replace whatever words you have.