我正在研究CS50的情绪挑战,我想使用Termcolor和占位符在控制台中打印颜色,但我有一些问题。
这是我的代码:
if score > 0:
green = lambda x: colored(x, 'green')
print(green("1 ", tweets))
elif score < 0:
red = lambda x: colored(x, 'red')
print(red(tweets))
else:
yellow = lambda x: colored(x, 'yellow')
print(yellow(tweets))
我想根据分数(绿色,红色或黄色)打印推文,没关系,代码适用于lambda x,但我也希望在推文之前打印一个数字颜色。
我已经尝试过lambda x,但是我有一个错误:
if score > 0:
green = lambda x, y: colored(x, y, 'green')
print(green("1 ", tweets))
Traceback (most recent call last):
File "./tweets", line 47, in <module>
main()
File "./tweets", line 39, in main
print(green("1 ", tweets))
File "./tweets", line 38, in <lambda>
green = lambda x, y: colored(x, y, 'green')
File "/usr/lib/python3/dist-packages/termcolor.py", line 105, in colored
text = fmt_str % (COLORS[color], text)
KeyError: 'Building Augmented Reality Experiences with Unity3D (and @Microsoft @HoloLens) by @shekitup at @CS50 at @Harvard,'
这就是我要打印的内容:
1 + (tweets) in green if positive
-1 + (tweets) in red if negative
0 + (tweets) in yellow if neutral
答案 0 :(得分:1)
这种方式对您的代码有意义吗?
(此语法仅适用于python&gt; = 3.5,解压缩的参数应该是最后一个,以避免在先前版本中出现歧义)
if score > 0:
green = lambda x: colored(*x, 'green')
print(green(["1 ", tweets]))
你传递一个参数列表,单独推文,或号码和推文,然后在lambda中解压缩
答案 1 :(得分:1)
你可以创建一个子任务并调用它:
def show_tweets_by_color(num, col, tweets):
green = lambda x: colored(x, 'green')
print(colored(str(num), " green") + green(tweets))
if score > 0:
show_tweets_by_color(1, "green", tweets)
...