2017-09-26 67 views
1

Python新手...我的願望是讓每一個字符或行或任何​​您認爲最適合ASCII的外觀。基本上我已經嘗試colorma我認爲這是它被稱爲,它只是基於一種顏色。所以在這裏,問你們什麼是最好的方法。我有什麼是Python - 使每個字符/行隨機彩色打印?

print(""" 


    _____ _    _      __ _    
/____| |   | |     /_| |    
| (___ | |_ __ _ ___| | _______ _____ _ __| |_| | _____  __ 
    \___ \| __/ _` |/ __| |//_ \ \// _ \ '__| _| |/ _ \ \ /\// 
    ____) | || (_| | (__| < (_) \ V/__/ | | | | | (_) \ V V/
|_____/ \__\__,_|\___|_|\_\___/ \_/ \___|_| |_| |_|\___/ \_/\_/ 




    """) 

這就是它。讓我通過這個知道你的想法! :)

回答

2

由colorama提供的有效前景色是colorama.Fore上的變量。我們可以使用vars(colorama.Fore).values()來檢索它們。我們可以通過使用random.choice來隨機選擇前景色,爲其提供vars獲得的前景色。

然後我們簡單地套用一個隨機選擇的顏色,每一個字符:

text = """ 


    _____ _    _      __ _    
/____| |   | |     /_| |    
| (___ | |_ __ _ ___| | _______ _____ _ __| |_| | _____  __ 
    \___ \| __/ _` |/ __| |//_ \ \// _ \ '__| _| |/ _ \ \ /\// 
    ____) | || (_| | (__| < (_) \ V/__/ | | | | | (_) \ V V/
|_____/ \__\__,_|\___|_|\_\___/ \_/ \___|_| |_| |_|\___/ \_/\_/ 




    """ 

import colorama 
import random 

colors = list(vars(colorama.Fore).values()) 
colored_chars = [random.choice(colors) + char for char in text] 

print(''.join(colored_chars)) 

這將打印出不同的顏色的每一個字符:

color characters

如果你想彩色線條代替,這是一個簡單的變化:

colored_lines = [random.choice(colors) + line for line in text.split('\n')] 
print('\n'.join(colored_lines)) 

enter image description here

您可以根據需要定製顏色列表。舉例來說,如果你想刪除它可能類似於您的終端背景(黑色,白色等)的顏色,你可以這樣寫:

bad_colors = ['BLACK', 'WHITE', 'LIGHTBLACK_EX', 'RESET'] 
codes = vars(colorama.Fore) 
colors = [codes[color] for color in codes if color not in bad_colors] 
colored_chars = [random.choice(colors) + char for char in text] 

print(''.join(colored_chars)) 

其中給出:

enter image description here

+0

直美!非常感謝你! – WeInThis

+0

我希望我可以移除黑色,因爲CMD,但我認爲它會很好:)如果它很容易去除黑色只。會很棒! – WeInThis

+0

哦。我現在確實有黑色的顏色,但是如何在這種情況下將其從值中刪除?有沒有可能的代碼只是刪除而不是改變整個代碼? :) – WeInThis