如何在python上打印特定的彩色单词?

2024-05-06 12:04:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打印一个特定的单词,每次它出现在文本中时,都会用不同的颜色。在现有代码中,我打印了包含相关单词“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,但不知道在哪里用。我想用它把“一”这个词换成不同的颜色。在

输出(第节)

44814 Ohhh that's the one Johnson told us about...can you send it to me? 44870 Kinda... I went but no one else did, I so just went with Sarah to get lunch xP 44951 No, it was directed in one place loudly and stopped when I stoppedmore or less 44961 Because it raised awareness but no one acted on their new awareness, I guess 44984 We need to do a fob analysis like our mcs onec

谢谢你


Tags: totextinimportjson颜色itcorpus
3条回答

也可以在字符串中使用ANSI color codes

# 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)

如果你只有一个颜色词,你可以用这个词,你可以扩展n个颜色词的逻辑:

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

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

我使用颜色模块from this link或彩色模块that link 此外,如果您不想使用一个模块来着色,可以寻址到this linkthat link

相关问题 更多 >