# coding:utf-8
import os
from win32com.client import Dispatch
def get_string_index(substring, string):
"""
获取同一字符串中的多个相同字符串的起始索引
:param substring: 需查找的字符串
:param string: 被查找的字符串
:return:
"""
indices = []
index = string.find(substring)
while index != -1:
indices.append(index)
index = string.find(substring, index + 1)
return indices
def word_underline_text(input_path, substring, out_path=None):
"""
给Word文档中的指定字符下划线
:param input_path: word文件路径
:param substring: 需划线的字符
:param out_path: 输出文件路径
:return:
"""
if not out_path:
out_path = f'{os.path.splitext(input_path)[0]}_注释{os.path.splitext(input_path)[1]}'
app = Dispatch('Word.Application')
app.Visible = 0
doc = app.Documents.Open(input_path)
for paragraph in doc.paragraphs:
index_list = get_string_index(substring, paragraph.Range.Text)
for idx in index_list:
for x in range(len(substring)):
paragraph.Range.Characters(idx + x + 1).Font.Underline = 6 # 设置下划线
paragraph.Range.Font.UnderlineColor = 255 # 设置下划线颜色为红色
doc.SaveAs(out_path)
app.Quit()
标签:index,word,下划线,python,substring,path,out,string
From: https://www.cnblogs.com/rong-z/p/17877161.html