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,但我不知道在哪里使用它。我想用它来让“一个”这个词变成不同的颜色。

输出(部分)

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

谢谢

4

3 回答 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)
于 2018-10-23T10:27:06.610 回答
1

如果您只有 1 个彩色单词,我认为您可以使用它,您可以扩展 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

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

于 2018-10-23T10:09:03.827 回答
0

我使用此链接中的颜色模块或链接的彩色模块此外 ,如果您不想使用模块进行着色,您可以访问此链接该链接

于 2018-10-23T10:17:19.263 回答