小编Viv*_*ngh的帖子

使用 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)

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

python python-docx

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×1

python-docx ×1