简体   繁体   中英

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?

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

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' .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM