Highlight text in python and save it to text file

I am trying to grab text from a text file and highlight the required text and aging wants to save the text in a new text file.

I can highlight text using ANSI escape sequences, but I cannot add it back to the word file.

from docx import Document
doc = Document('t.docx')
##string present in t.docx '''gnjdkgdf helloworld dnvjk dsfgdzfh jsdfKSf klasdfdf sdfvgzjcv'''

if 'helloworld' in doc.paragraphs[0].text:    
    high=doc.paragraphs[0].text.replace('helloworld', '\033[43m{}\033[m'.format('helloworld'))


doc.add_paragraph(high)
doc.save('t1.docx')

      

get this error.

ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters

      

+3


source to share


1 answer


Instead of using ANSI escape sequences, you can use the python-docx

built-in Font Highlight Color :

screenshot



from docx import Document
from docx.enum.text import WD_COLOR_INDEX

doc = Document('t.docx')
##string present in t.docx '''gnjdkgdf helloworld dnvjk dsfgdzfh jsdfKSf klasdfdf sdfvgzjcv'''

# Get the first paragraph text
p1_text = doc.paragraphs[0].text

# Create a new paragraph with "helloworld" highlighted
p2 = doc.add_paragraph()
substrings = p1_text.split('helloworld')
for substring in substrings[:-1]:
    p2.add_run(substring)
    font = p2.add_run('helloworld').font
    font.highlight_color = WD_COLOR_INDEX.YELLOW
p2.add_run(substrings[-1])

# Save document under new name
doc.save('t1.docx')

      

+1


source







All Articles