我编写了这个函数,使用 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
最佳答案
您的代码的问题在于您正在替换整个文本
。另外,我认为你应该在模式中转义关键字
,而不是在替换中!试试这个:
def highlight_one(text, keyword):
replacement = "\033[91m" + keyword + "\033[39m"
text = re.sub(re.escape(keyword), replacement, text, flags=re.I)
print text
如果您想突出显示多个关键字(作为列表传递),您确实可以使用 |
将它们连接起来,然后使用 \1
来引用更换。
def highlight_many(text, keywords):
replacement = "\033[91m" + "\\1" + "\033[39m"
text = re.sub("(" + "|".join(map(re.escape, keywords)) + ")", replacement, text, flags=re.I)
print text
如果你想要更多的控制,你也可以使用可调用的;匹配作为参数传递。
def highlight_many(text, keywords):
replacement = lambda match: "\033[91m" + match.group() + "\033[39m"
text = re.sub("|".join(map(re.escape, keywords)), replacement, text, flags=re.I)
print text
关于python - 使用正则表达式功能突出显示多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32142877/