【发布时间】:2017-04-17 03:15:31
【问题描述】:
我编写了这个函数,它使用 ANSI 转义颜色突出显示一个单词。 \033[91m 为红色,\033[39m 为“重置”。
def highlight(text, keyword):
text = text.replace(keyword, "\033[91m" + keyword + "\033[39m")
print text
highlight("This word is red.", "word")
问:我的问题是该函数无法处理多个关键字来突出显示(最好可以在keyword 中输入任意数量的单词)。它也不区分大小写。我能做些什么来解决这个问题?
我想一种选择是使用re.sub,也许使用| 和flags=re.I 忽略大小写来分隔关键字。我做了各种尝试,但我没有到达那里。
这个例子正确地突出了这个词,但不幸的是丢弃了除了这个词本身之外的所有东西。它也不能处理多个单词。
def highlight(text, keyword):
regex = "\033[91m" + re.escape(keyword) + "\033[39m"
text = re.sub(text, regex, text, flags=re.I)
print text
【问题讨论】:
标签: python regex python-2.7