高亮word特定关键字(python)
第一次写博客,主要是记录一些日常写下的代码,算是记录,也为了自己之后便于查找。
今天主要是写一个利用python对word的内容进行操作,具体是指高亮特定的文字。
首先,导入包(安装python-docx)
from docx import Documentfrom docx.shared import RGBColor,Ptfrom docx.enum.text imp写一个函数,对word中的每一段遍历读取查找,并修改run的属性```pythondef getP(paragraph,keyword):for r in paragraph.runs:font_size = r.font.sizebold = r.boldcolor = r.font.color.rgbhighlight_color = r.font.highlight_colorrest = r.text.split(keyword)r.text = ''for text in rest[:-1]:run = paragraph.add_run(text=text)set_run(run, font_size, bold, color,highlight_color)run = paragraph.add_run(keyword)run.font.size = font_sizerun.bold = boldrun.font.color.rgb = colorrun.font.highlight_color = WD_COLOR_INDEX.YELLOW # 加上自己要修改的类型run = paragraph.add_run(rest[-1])set_run(run, font_size, bold, color,highlight_color)
函数的调用也很简单,直接读取,修改,保存即可
keywords = ['word','python']file_path = r'try.docx'docx = Document(file_path)for keyword in keywords:for paragraph in docx.paragraphs:getP(paragraph,keyword)docx.save(file_path)
之后的其他属性也可以在函数中加以修改、
python将word文档指定内容标红