如何在Python中以彩色打印指定单词?

3

我希望每次在文本中出现特定单词时,能以不同的颜色打印该单词。在现有代码中,我已经打印了包含相关单词“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')

我导入了 Fore,但不知道在哪里使用它。我想用它来让单词 "one" 以不同的颜色显示。 输出(部分内容): 44814 哦,那就是约翰逊告诉我们的那个……你能把它发给我吗? 44870 有点……我去了,但没有其他人去,所以我和莎拉一起去吃午饭 xP 44951 不,它是在一个地方大声指引,当我停下来时它就停下来了,或多或少 44961 因为它提高了人们的意识,但没有人采取行动,我想 44984 我们需要像我们的 mcs onec 那样进行 fob 分析 谢谢

2
可能是 如何在 Python 终端中打印彩色文本? 的重复问题。 - Nazim Kerimbekov
3个回答

2
您也可以在字符串中使用ANSI颜色代码:(参考链接)
# 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)

1

如果你只有一个有颜色的单词,我认为你可以使用这个方法,你可以根据需要扩展逻辑以支持多个有颜色的单词:

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

我认为这是一个丑陋的解决方案,甚至不确定它是否有效。但如果你找不到其他解决方案,这也算是一个解决方案。


0

1
嗨!请尽量避免只提供链接的答案,而是尝试发布一个短的示例,将您正在引用的信息结合起来! - Oliver Baumann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接