【问题标题】:Highlight multiple words using Regex function使用 Regex 函数突出显示多个单词
【发布时间】: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


    【解决方案1】:

    您的代码的问题在于您要替换整个 text。另外,我认为您应该在 pattern 中转义 keyword,而不是在替换中!试试这个:

    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
    

    【讨论】:

    • 您还应该能够使用 .format 来使这对 python3 更友好,例如 replacement = "\033[91m{}\033[39m".format(keyword) 。请注意,python 2.5 及更低版本没有 .format 和 2.6 我相信需要您使用 {0} 而不是 {} - RTFM 更多
    猜你喜欢
    • 2015-11-13
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    相关资源
    最近更新 更多