突出显示python中的文本并将其保存在word文件中

问题描述 投票:4回答:1

我试图从word文件中取出文本并突出显示所需的文本和老化想要将文本保存到新的word文件中。

我能够使用ANSI转义序列突出显示文本,但我无法将其添加回word文件。

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')

得到这个错误。

ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters
python-3.x python-docx
1个回答
2
投票

您可以使用python-docx的内置Font highlight color,而不是使用ANSI转义序列:

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's 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')
© www.soinside.com 2019 - 2024. All rights reserved.