Reputation: 966
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?
Upvotes: 0
Views: 924
Reputation: 3224
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.
Upvotes: 1
Reputation: 51807
You could always do this (though it's probably a little slow):
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
might also be interesting here, especially since you probably don't want to replace words that are inside other words so you could use r'\bword\b'
.
Upvotes: 1
Reputation: 8011
This should work:
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
Upvotes: 2