使用 python-docx 突出显示文本

Viv*_*ngh 3 python python-docx

我想突出显示 docx 中的文本并将其保存到另一个文件。这是我的代码

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[i].text).encode('ascii'))
                if 'vehicle' in inline[i].text:
                    x=inline[i].text.split('vehicle')
                    inline[i].clear()
                    for j in range(len(x)-1):
                        inline[i].add_text(x[j])
                        y=inline[i].add_text('vehicle')
                        y.highlight_color='YELLOW'
            # print (p.text)

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

    highlight_text('t1.docx')
Run Code Online (Sandbox Code Playgroud)

这个词没有突出显示我做错了什么。

sca*_*nny 5

突出显示是字体的一个属性,而不是直接运行。另外,Run.add_text()返回一个_Text对象,而不是一次运行。

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
Run Code Online (Sandbox Code Playgroud)

此外,突出显示应用于整个运行,因此您需要为“vehicle”之前的每个文本、“vehicle”单词本身以及“vehicle”之后的文本创建单独的运行。

此外,不能保证给定的单词在单次运行中完全出现;运行经常在一个单词内分开。因此,您需要采用更复杂的方法来处理一般情况。

所以这里还有很多工作要做,但这应该让您至少看到一些黄色突出显示:)