在 Python 中突出显示字符串中的多个子字符串

Highlight Multiple Substrings in a String in Python

我想在 python.

中突出显示列表中存在于另一个字符串中的子字符串

我有一个名为 highlight_list 的列表:

highlight_list=['cat','dog','catdog']

我有一个名为 text_main 的字符串:

text_main='The cat and the dog were dancing together.  They looked like a catdog, not a dogcat'

我希望输出是一个名为 text_highlight 的字符串,如下所示:

text_highlight

一起跳舞。它们看起来像 catdog,而不是 dogcat

而不是粗体,可能是黄色荧光笔块填充或其他东西。

我试过加入他们,然后使用 string.replace 但这没有用 - 像这样:

highlight_str='|'.join(highlight_list)
text_highlight=text_main.replace(highlight_str, '3[44;33m{}3[m'.format(text_main)))

在您的代码中,您使用 3[44;33m{}3[m'.format(text_main) 这将使整个文本着色。

您可以使用 re.sub 而不是替换,并使匹配项而不是整个字符串着色。

您可以 highlight_str 在词边界 \b 之间使用非捕获组 (?: 来防止部分匹配。

highlight_str = r"\b(?:" + '|'.join(highlight_list) + r")\b"

图案看起来像

\b(?:cat|dog|catdog)\b

例如

import re

text_main = 'The cat and the dog were dancing together.  They looked like a catdog, not a dogcat'
highlight_list = ['cat', 'dog', 'catdog']
highlight_str = r"\b(?:" + '|'.join(highlight_list) + r")\b"
text_highlight = re.sub(highlight_str, '3[44;33m\g<0>3[m', text_main)
print(text_highlight)