高亮顯示word中指定字型顏色,用python實現比較麻煩,用word 宏實現更容易,效率也更高。當然python擴充套件效能更好,所以也嘗試用python實現。
由於python-docx外掛需要分開段落和表格讀取,應此需要分開操作。段落的處理速度比較快,小型表格處理也還可以,幾百行到上千行的就很慢了。
首先安裝Python支援word外掛,然後匯入。
from docx import Documentfrom docx.shared import RGBColor, Ptfrom docx.enum.text import WD_COLOR_INDEX
呼叫方式:
file = Document("C:/xx.doc") paragraphs_utils(file,"你","paragraphs")
具體功能實現,對於表格就是讀取其中的cell,再執行一遍查詢就可以了。
# highlight關鍵字的所有自然段def sub_highlight(par_obj, replaceword, str_type): # 自然段遍歷程式 global all_length for p in par_obj.paragraphs: # 遍歷所有自然段 if str_type == "paragraphs": # 區別段落和表格,表格直接處理 all_length = all_length + 1 progress_bar() if replaceword in p.text: # print(file.paragraphs[i].text)加快速度 for r in p.runs: # 遍歷自然段的所有格式(run) if r.text != "": # 把空的run過濾掉,加快速度 font_size = r.font.size # 把原來的字型型別賦值給setrun的三個變數 bold = r.bold color = r.font.color.rgb highlight_color = r.font.highlight_color rest = r.text.split(replaceword) # 需要修改型別的文字作為分隔符切分 r.text = '' # 清空原有run文字 for text in rest[:-1]: run = p.add_run(text) set_run(run, font_size, bold, color, highlight_color) run = p.add_run(replaceword) run.font.size = font_size # 把原來的字型型別從setrun賦值回來 run.bold = bold run.font.highlight_color = WD_COLOR_INDEX.YELLOW # 加上自己要修改的型別 run = p.add_run(rest[-1]) set_run(run, font_size, bold, color, highlight_color)
執行完效果。
最新評論