python高亮顯示word指定文字或改變顏色

2021-10-19 14:20:07 字數 1680 閱讀 9423

高亮顯示word中指定字型顏色,用python實現比較麻煩,用word 巨集實現更容易,效率也更高。當然python擴充套件效能更好,所以也嘗試用python實現。

由於python-docx外掛程式需要分開段落和**讀取,應此需要分開操作。段落的處理速度比較快,小型**處理也還可以,幾百行到上千行的就很慢了。

首先安裝python支援word外掛程式,然後匯入。

from docx import document

from docx.shared import rgbcolor, pt

from 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)

執行完效果。

lucene高亮顯示

lucene針對高亮顯示功能提供了兩種實現方式,分別是highlighter和fastvectorhighlighter 顧名思義,fastvectorhighlighter較highlighter速度更快,功能也更強大,但是有使用前提 建立索引時,需要儲存field的分詞向量資訊 termvect...

solr高亮顯示

2012 12 14 15 56 3974人閱讀收藏 舉報solr是在lucene的基礎上做的開發,那麼在某些功能的實現上,與lucene也會有相似之處。solr的高亮顯示 包括自動摘要 是通過hl這個param,以及其相關變數來實現的,hl是hightlight的簡寫。lucene中是通過high...

lucene 高亮顯示

lucene針對高亮顯示功能提供了兩種實現方式,分別是highlighter和fastvectorhighlighter。顧名思義,fastvectorhighlighter較highlighter速度更快,功能也更強大,但是有使用前提 建立索引時,需要儲存field的分詞向量資訊。termvect...