Thomas Reynaud Thomas Reynaud - 2 months ago 7
Python Question

Coloring given words in a text with Python

I have already read the questions about how coloring text with Python and the Colorama package but I didn't find what I was looking for.

I have some raw 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.


And two lists of words:

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


I would like to print that text in a terminal so that words in
good
are displayed in green and words in
bad
are displayed in red.

I know I could use colorama, check each word sequentially and make a print statement for this word but it doesn't sound like a good solution. Is there an effective way to do that?

Answer

Here is a solution using map. It's definitely no faster than conventional looping :/

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())))

Or alternatively:

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

The second version is probably better.

Comments