Coloring given words in a text with Python
<p>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.</p>

<p>I have some raw text:</p>

<blockquote>
  <p>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.</p>
</blockquote>

<p>And two lists of words:</p>

<pre><code>good = ["instrument", "kind", "exquisite", "young"]
bad  = ["impossible", "unpleasant", "woody"]
</code></pre>

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

<p>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?</p>

<p>You could always do this (though it's probably a little slow):</p>

<pre><code>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)
</code></pre>

<p><code>re.sub</code> might also be interesting here, especially since you probably don't want to replace words that are inside other words so you could use <code>r'\bword\b'</code>.</p>

python