highlight text using python-docx

爱⌒轻易说出口 提交于 2019-12-06 04:13:26

Highlighting is an attribute of a font, not a run directly. Also, Run.add_text() returns a _Text object, not a run.

from docx.enum.text import WD_COLOR_INDEX

for paragraph in document.paragraphs:
    if 'vehicle' in paragraph.text:
        for run in paragraph.runs:
            if 'vehicle' in run.text:
                x = run.text.split('vehicle')
                run.clear()
                for i in range(len(x)-1):
                    run.add_text(x[i])
                    run.add_text('vehicle')
                    run.font.highlight_color = WD_COLOR_INDEX.YELLOW

Also, a highlight is applied to the entire run, so you need to create a separate runs for each of the text before "vehicle", the "vehicle" word itself, and the text after "vehicle".

Also, there's no guarantee that a given word appears completely within a single run; runs often split within a word. So you'll need to be more sophisticated in your approach to handle the general case.

So there's quite a bit more work to do here, but this should get you seeing at least some yellow highlighting :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!