Python高亮文本中的关键词

print

全部高亮

w = '比赛'
t = '比赛开始没多久就结束了比赛,现在没有比赛'

def replace_color(text, word):
    new_word = '\033[031m' + word + '\033[0m'  # red
    len_w = len(word)
    len_t = len(text)
    for i in range(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))

mysql高亮查询

def highlight(self, field, table, keyword, n=99):
    sql = "SELECT %s FROM %s WHERE INSTR(%s,'%s')>0;" % (field, table, field, keyword)
    for i in self.fetchone(sql, n):
        text = i[0]
        highlight_word = '\033[031m' + keyword + '\033[0m'  # red
        len_w = len(keyword)
        len_t = len(text)
        for i in range(len_t - len_w, -1, -1):
            if text[i: i + len_w] == keyword:
                text = text[:i] + highlight_word + text[i + len_w
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值