代码:
from docx import Document
from docx.shared import RGBColor
obj= Document('装机必读调整样式.docx')
word ='软件'
def set_run(run):#设置run的字体大小、是否加粗以及字体颜色run.font.size = font_sizerun.bold = boldrun.font.color.rgb= color
for p in obj.paragraphs:for r in p.runs:if word not in r.text:pass#获取当前run的字体属性font_size =r.font.sizebold =r.boldcolor =r.font.color.rgb#使用关键词切分当前run的文本rest =r.text.split(word)#清除当前run的内容r.text = ''for text in rest[:-1]:run = p.add_run(text=text)set_run(run)run = p.add_run(word)run.font.size = font_sizerun.bold = boldrun.font.color.rgb=RGBColor(255,0,0)run = p.add_run(rest[-1])set_run(run)obj.save('装机必读调整之后样式.docx')
执行结果: