用Python为文本中的给定单词着色

2024-04-28 03:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经读过关于如何用Python和Colorama包给文本着色的问题,但是我没有找到我想要的。你知道吗

我有一些原始文本:

Impossible considered invitation him men instrument saw celebrated unpleasant. Put rest and must set kind next many near nay. He exquisite continued explained middleton am. Voice hours young woody has she think equal.

还有两个单词列表:

good = ["instrument", "kind", "exquisite", "young"]
bad  = ["impossible", "unpleasant", "woody"]

我想在终端中打印该文本,以便good中的单词显示为绿色,bad中的单词显示为红色。你知道吗

我知道我可以使用colorama,按顺序检查每个单词,并为这个单词做一个打印语句,但这听起来不是一个好的解决方案。有没有有效的方法?你知道吗


Tags: 文本单词coloramabadgood着色invitationinstrument
3条回答

这应该起作用:

from colorama import Fore, Style

for word in text.split(' '):
    if word in good:
        print Fore.red + word
    elif word in bad:
        print Fore.green + word
    else:
        print Style.RESET_ALL + word

你可以一直这样做(尽管可能有点慢):

from colorama import Fore

for word in good:
    text = text.replace(word, Fore.GREEN+word)

for word in bad:
    text = text.replace(word, Fore.RED+word)

print(text)

re.sub在这里可能也很有趣,特别是因为您可能不想替换其他单词中的单词,所以可以使用r'\bword\b'。你知道吗

下面是一个使用map的解决方案。它绝对不比传统的循环快:/

from colorama import Fore, Style

def colourise(s, good, bad):
    if s in good:
        return Fore.RED + s
    elif s in bad:
        return Fore.GREEN + s
    else:
        return Style.RESET_ALL + s

text = "Impossible considered invitation him men instrument saw celebrated unpleasant. Put rest and must set kind next many near nay. He exquisite continued explained middleton am. Voice hours young woody has she think equal."

good = ["instrument", "kind", "exquisite", "young"]
bad  = ["impossible", "unpleasant", "woody"]
print(' '.join(map(lambda s: colourise(s, good, bad),text.split())))

或者:

print(' '.join(colourise(s, good, bad) for s in text.split()))

第二种可能更好。你知道吗

相关问题 更多 >