Search code examples
pythoncolorsformattinghighlighting

How to add colour to a specific word in a string?


I want to print a notice to the program user. Here's my code:

class Colour:
   PURPLE = '\033[95m'
   CYAN = '\033[96m'
   DARKCYAN = '\033[36m'
   BLUE = '\033[94m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   RED = '\033[91m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'

import pickle
import string
import re
from Colour import Colour

wordFile = open("texts/words2.txt", "r")
alpha = "abcdefghijklmnopqrstuvxwyz"
wordList = []
linesInFile = {}
lineCounter = 0
mispelled = []

for line in wordFile:
    linesInFile.update({lineCounter:line})
    lineCounter += 1
    for word in line.split():
        word = ''.join(ch for ch in word if ch not in string.punctuation)
        wordList.append(re.sub("[^a-z]", "", word.lower()))

trie = pickle.load(open("Pickled Trees/trie.pkl", "rb"))
trieList = trie.list("", [])

for word in wordList:
    if word not in trieList:
        if len(word) > 1:
            mispelled.append(word)

for key, value in linesInFile.items():
    if mispelled[0] in value:
        print(Colour.RED + "================ERROR================")
        print("The program found an error on line " + Colour.RED + str(key) + Colour.END)
        print(Colour.RED + "================ERROR================")

Right now, this will print the following:

================ERROR================
The program found an error on line 57
================ERROR================

However, I want it to print so that only the header, footer and line number are red. As it is, the entire output is red, I don't want "The program found an error on line" to be red.


Solution

  • You need to add Colour.END to the header and footer lines. So that the red color won't continue with the second line. Add it to end of each line.

    print(Colour.RED + "================ERROR================" + Colour.END)
    print("The program found an error on line " + Colour.RED + str(key) + Colour.END)
    print(Colour.RED + "================ERROR================" + Colour.END)