2017-07-08 48 views
2

我正在處理CS50的情感挑戰,我想用顏色使用Termcolor和佔位符在控制檯中打印,但我遇到了一些問題。placecolor in termcolor python

這是我的代碼:

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

我想根據得分(綠色,紅色或黃色),這是很正常打印的鳴叫,代碼和λX的效果很好,但我想也在相同顏色的推文之前打印一個數字。

我試過的λX,Y,但我有一個錯誤:

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 

回答

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) 
... 
+0

我已經嘗試過這樣的事情,你的解決方案我有一個錯誤:lambda調用的位置參數太多 – Sebastiano

+0

@Sebastiano我做了一個編輯,讓我知道如果這個作品 –

+0

nop,但我找到一個解決方案:打印(彩色(「1」,「綠色」)+綠色(鳴叫))也許有一種方法更容易 – Sebastiano

1

這是否有意義的方式與您的代碼?

(這句法僅適用於蟒蛇> = 3.5,解壓參數應該是最後的,以避免在以前的版本歧義)

if score > 0: 
    green = lambda x: colored(*x, 'green') 
    print(green(["1 ", tweets])) 

你傳遞參數的清單,單獨鳴叫,或數量和鳴叫,然後在lambda解壓真實

+0

這樣,我有一個錯誤:語法錯誤:只有命名的參數可以遵循*表達 – Sebastiano

+0

@sebastiano,我很好奇重現這一點,你使用什麼版本的Python? – PRMoureu

+0

Cloud9中的Python 3與CS50 IDE – Sebastiano