w ='比赛'
t ='比赛开始没多久就结束了比赛,现在没有比赛'defreplace_color(text, word):
new_word ='\033[031m'+ word +'\033[0m'# red
len_w =len(word)
len_t =len(text)for i inrange(len_t - len_w,-1,-1):if text[i: i + len_w]== word:
text = text[:i]+ new_word + text[i + len_w:]return text
print(t)print(replace_color(t, w))
单个高亮
from jieba import tokenize
text ='我用小米手机订购了一袋小米'
entity ='小米'
replace_color =lambda word:'\033[033m'+ word +'\033[0m'
replace_word =lambda sentence, word, head, tail: sentence[:head]+ word + sentence[tail:]for word, head, tail in tokenize(text):if word == entity:
word = replace_color(word)print(replace_word(text, word, head, tail))