还差几 2022-07-26 10:16 采纳率: 25%
浏览 86
已结题

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

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

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

3条回答 默认 最新

  • eq0284 2022-07-26 15:30
    关注
    
    # 修改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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 8月4日
  • 已采纳回答 7月27日
  • 赞助了问题酬金15元 7月26日
  • 修改了问题 7月26日
  • 展开全部

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图