我想每次出现在文本中时以不同的颜色打印一个特定的单词。在现有代码中,我已打印出包含相关单词“ 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 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
谢谢
答案 0 :(得分: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
我认为这是一个丑陋的解决方案,甚至不确定它是否有效。但这是解决方案,如果您找不到其他任何东西。
答案 1 :(得分:1)
您也可以在字符串中使用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)
答案 2 :(得分:0)
我使用颜色模块from this link或颜色模块that link 此外,如果您不想使用模块进行着色,则可以访问this link或that link