3

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

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Yeng
  • 53
  • 2
  • 7
  • 2
    Possible duplicate of [How to print colored text in terminal in Python?](https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python) – Nazim Kerimbekov Apr 30 '19 at 21:40

3 Answers3

2

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)
Oliver Baumann
  • 2,209
  • 1
  • 10
  • 26
1

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.

Alexis Drakopoulos
  • 1,115
  • 7
  • 22
0

i use colour module from this link or colored module that link Furthermore if you dont want to use a module for coloring you can address to this link or that link

Anagnostou John
  • 498
  • 5
  • 14
  • 1
    Hi! Please try to avoid link-only answers and instead try and post a short example incoroporating the information you are referencing! – Oliver Baumann Oct 23 '18 at 10:18