How to print specific words in colour on python?

Viewed 2530

I want to print a specific word a different color every time it appears in the text. In the existing code, I've printed the lines that contain the relevant 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 have the word "one" in a different color.

output (section of)

44814 Ohhh that's the one Johnson told us about...can you send it to me? 44870 Kinda... I went but no one else did, I so just went with Sarah to get lunch xP 44951 No, it was directed in one place loudly and stopped when I stoppedmore or less 44961 Because it raised awareness but no one acted on their new awareness, I guess 44984 We need to do a fob analysis like our mcs onec

Thank you

3 Answers

You could also just use the ANSI color codes in your strings:

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

If you only have 1 coloured word you can use this I think, you can expand the logic for n coloured words:

our_str = "Ohhh that's the one Johnson told us about...can you send it to me?"

def colour_one(our_str):

    if "one" in our_str:
        str1, str2 = our_str.split("one")

        new_str = str1 + Fore.RED + 'one' + Style.RESET_ALL + str2
    else:
        new_str = our_str        

    return new_str

I think this is an ugly solution, not even sure if it works. But it's a solution if you can't find anything else.

Related