I have to delete particular word in docx file so i am using logic replace with ""(empty string) I am sharing my code:
def docx_replace_regex(doc_obj, regex, replace):
for p in doc_obj.paragraphs:
if regex.search(p.text):
inline = p.runs
# Loop added to work with runs (strings with same style)
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"sign")
replace1 = r""
filename = r"C:\...\sample01.docx"
doc = Document(filename)
docx_replace_regex(doc, regex1, replace1)
doc.save('sample01.docx')
Now the issue i am facing is that suppose we have a word "Design" in docx file and i have given "sign" as replacing word, so "Design" is changing to "De" which is ideally not correct. Can any one help me out.