【问题标题】:How to add colour to a specific word in a string? [duplicate]如何为字符串中的特定单词添加颜色? [复制]
【发布时间】:2016-09-19 22:08:50
【问题描述】:

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

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================")

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

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

但是,我希望它打印出来,以便只有页眉、页脚和行号是红色的。事实上,整个输出都是红色的,我不希望“程序在线发现错误”是红色的。

【问题讨论】:

标签: python colors formatting highlighting


【解决方案1】:

您需要将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)

【讨论】:

    猜你喜欢
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2011-06-05
    • 1970-01-01
    • 2020-07-04
    • 2015-10-19
    相关资源
    最近更新 更多