【问题标题】:Python: highlight word or phrase in long stringPython:突出显示长字符串中的单词或短语
【发布时间】:2021-07-30 19:57:04
【问题描述】:

我有一长串句子,我正在尝试使用 ANSI 颜色代码来突出显示匹配的字符串。输入不区分大小写,但我希望输出(即正匹配)保持区分大小写。

#!/usr/bin/env python3

from re import sub, IGNORECASE

red = '\033[31m'
nul = '\033[0m'

sentences = ["foo foo findme 123 bar bar",
             "foo findme foo bar 123 bar",
             "foo foo FindME 123 bar bar"]

for sentence in sentences:
    search_term = "findme 123"
    sentence = sub(search_term.replace(' ', '.*'), f'{red}{search_term}{nul}', sentence, flags=IGNORECASE)
    print(sentence)

当前输出:

foo foo findme 123 bar bar # this is good
foo findme 123 bar         # this is bad
foo foo findme 123 bar bar # this is bad

期望的输出:

foo foo findme 123 bar bar
foo foo FindME 123 bar bar

如何正确匹配区分大小写的字符串并防止误报破坏句子的某些部分?

我非常愿意使用 re 以外的库来解决这个问题,但通常更喜欢纯 python3 方法。

【问题讨论】:

    标签: python python-3.x regex string replace


    【解决方案1】:

    试试:

    import re
    
    red = "\033[31m"
    nul = "\033[0m"
    
    sentences = [
        "foo foo findme 123 bar bar",
        "foo findme foo bar 123 bar",
        "foo foo FindME 123 bar bar",
    ]
    
    s = "findme 123"
    
    for sentence in sentences:
        sentence = re.sub(
            r"\b({})\b".format(re.escape(s)),
            r"{}\1{}".format(red, nul),
            sentence,
            flags=re.I,
        )
        print(sentence)
    

    打印(截图):

    【讨论】:

    • 谢谢,安德烈。这适用于上述示例脚本,但由于某种原因不适用于我的实际脚本。你能解释一下 `r"\b({})\b"` 的作用吗?我发现 `r"({})"` 在我的实际脚本中适用于不包含空格的搜索(例如,“findme”有效,“findme 1”无效)。
    • @zihobu \b 是“单词边界”。你可以看到regex here
    • 感谢您的帮助。这有点不相关,但为什么你更喜欢import re 而不是from re import ..., ..., ...?只导入我们需要的东西通常不是更好吗?
    • @zihobu 我个人我会做import re。对我来说,它更容易阅读。
    猜你喜欢
    • 2012-09-09
    • 2020-10-12
    • 2017-08-29
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多