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

Posted

技术标签:

【中文标题】如何为字符串中的特定单词添加颜色? [复制]【英文标题】: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================

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

【问题讨论】:

试试***.com/a/42528796/610569 【参考方案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)

【讨论】:

以上是关于如何为字符串中的特定单词添加颜色? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何为按钮文本asp.net的特定单词添加下划线

Xamarin Forms:如何为网格内单击的按钮添加背景颜色(单词搜索游戏)

如何为背景图像添加背景颜色? [复制]

如何为 uialertview 或 UIAlertController 中的特定单词着色? (迅速)

如何为列表中的每个项目添加一个布尔值?

如何为codeigniter中的特定列数据赋予颜色?