[Python] highlight text using python-docx

Discussão em 'Python' iniciado por Stack, Agosto 25, 2025.

  1. Stack

    Stack Membro Participativo

    I want to highlight text in docx and save it another file. here is my code

    from docx import Document

    def highlight_text(filename):

    doc = Document(filename)
    for p in doc.paragraphs:
    if 'vehicle' in p.text:
    inline = p.runs
    # print(inline)
    # Loop added to work with runs (strings with same style)
    for i in range(len(inline)):
    # print((inline.text).encode('ascii'))
    if 'vehicle' in inline.text:
    x=inline.text.split('vehicle')
    inline.clear()
    for j in range(len(x)-1):
    inline.add_text(x[j])
    y=inline.add_text('vehicle')
    y.highlight_color='YELLOW'
    # print (p.text)

    doc.save('t2.docx')
    return 1
    if __name__ == '__main__':

    highlight_text('t1.docx')


    word is not getting highlighted what i am doing wrong.

    Continue reading...

Compartilhe esta Página