Python – How do I print specific words in color on python?

How do I print specific words in color on python?… here is a solution to the problem.

How do I print specific words in color on python?

Every time it appears in text, I want to print a specific word in a different color. In the existing code, I printed a line containing the related word “one”.

import json
from colorama import Fore
fh = open(r"fle.json")
corpus = json.loads(fh.read())
for m in corpus['smsCorpus']['message']:
    identity = m['@id']
    text = m['text']['$']
    strtext = str(text)
    utterances = strtext.split()
    if 'one' in utterances:

print(identity,text, sep ='\t')

I

imported Fore, but I don’t know where to use it. I want to use it to display the word “one” in different colors.

Output (partial).

44814 Oh, that's the one Johnson told us... Can you send it to me?
44870 Sort of... I went, but no one went, so I just went to lunch with Sarah xP
44951 No, it is loudly pointed to a place, more or less when I stop
44961 because it raises consciousness, but no one acts on their new consciousness, I guess
44984 We need to do FOB analysis like our MCS OneC

Thanks

Solution

You can also just use ANSI color codes in your string:

# define aliases to the color-codes
red = "\033[31m"
green = "\033[32m"
blue = "\033[34m"
reset = "\033[39m"

t = "That was one hell of a show for a one man band!"
utterances = t.split()

if "one" in utterances:
    # figure out the list-indices of occurences of "one"
    idxs = [i for i, x in enumerate(utterances) if x == "one"]

# modify the occurences by wrapping them in ANSI sequences
    for i in idxs:
        utterances[i] = red + utterances[i] + reset

# join the list back into a string and print
utterances = " ".join(utterances)
print(utterances)

Related Problems and Solutions