简体   繁体   中英

Deleting a specific word in doc file using python

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.

It worked.! This is the 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"\bsign\b")
replace1 = r""
filename = r"C:\Users.........\sample01.docx"
doc = Document(filename)
docx_replace_regex(doc, regex1, replace1)
doc.save('sample01.docx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM