如何为字符串中的特定单词添加颜色?

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

我想向程序用户打印一条通知。这是我的代码:

class Colour:
   PURPLE = '3[95m'
   CYAN = '3[96m'
   DARKCYAN = '3[36m'
   BLUE = '3[94m'
   GREEN = '3[92m'
   YELLOW = '3[93m'
   RED = '3[91m'
   BOLD = '3[1m'
   UNDERLINE = '3[4m'
   END = '3[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================")

现在,这将打印以下内容:

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

但是,我希望它打印时只有页眉、页脚和行号是红色的。事实上,整个输出都是红色的,我不希望 "The program found an error on line" 是红色的。

您需要将 Colour.END 添加到页眉和页脚行。这样红色就不会在第二行继续。将其添加到每行的末尾。

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)