关于#python#的问题:如何用把word文档中括号内的文字标红

如何用把word文档中括号内(包括括号)的文字标红
查过很多别人的案例,但都是针对关键字,而括号里的内容会发生改变
如以下文本:
注意有中英文的括号

如何用把(word)文档(中)括号(内)的(文字)标红
如何用把wo(rd文档)中括号内的(文字标)红
如何用把(word)文档中括号内的(文字)标红

# 修改word字颜色
from docx import Document
from docx.shared import RGBColor
import re
# 高亮前文档
input = 'F:/aa.docx'
# 高亮后文档
output = 'F:/nn.docx'
# 高亮颜色
highlight_color = RGBColor(0, 0, 255)

def set_run(run,font_size,bold,color):
    #设置run的字体大小、是否加粗以及字体颜色
    run.font.size = font_size
    run.bold = bold
    run.font.color.rgb = color

file = Document(input)
for paragraph in file.paragraphs:
    for r in paragraph.runs:
        font_size = r.font.size
        bold = r.bold
        color = r.font.color.rgb

        highlight_index = [i.regs[0] for i in re.finditer(r'([^()]*$|^[^()]*?)|([^()]+)', r.text)]
        str = r.text
        r.text = ''
        i = 0
        for i in range(len(highlight_index)):
            current_index = highlight_index[i]
            run = paragraph.add_run(str[current_index[0]: current_index[1]])
            set_run(run, font_size, bold, highlight_color)
            if current_index[1] == len(str):
                break
            if i == len(highlight_index) - 1:
                run = paragraph.add_run(str[current_index[1]: len(str)])
                set_run(run, font_size, bold, color)
            else:
                run = paragraph.add_run(str[current_index[1]: highlight_index[i + 1][0]])
                set_run(run, font_size, bold, color)


file.save(output)

高亮前:

img

高亮后:

img

用正则找括号和其中文字

r'(\w*)'

用readline循环遍历word或者readlines(但是注意返回值是列表,要用列表的方式处理),然后把结果替换成红色

文章:python将word文档指定内容标红以及设置文字突出显示,即高亮 中也许有你想要的答案,请看下吧