2015-01-13 58 views
2

我試圖做一個Python程序,將接受文本輸入的參數,然後隨機改變每個字母是一個不同的顏色隨機顏色的文本發電機密封

這是我有:

color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white']; 

我想要能夠讓我輸入一個段落的程序,然後使用列表中的顏色並隨機將它們分配給每個字母。

對於輸出,我想成爲這樣的東西。

[color=random]H[/color][color=random]i[/color] [color=random]t[/color] [color=random]h[/color] [color=random]e[/color][color=random]r[/color][color=random]e[/color] 

顏色應該從我做的列表中隨機選擇。這可能嗎?

回答

1

這個工作對我來說:

from random import choice 

color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'] 
l = len(color) 

str = "Hit Here" 

html = '' 
for x in str: 
    html += '[color=' + choice(color) + ']' + x + '[/color]' if len(x.strip()) > 0 else x 

print(html) 

輸出示例:

[color=yellow]H[/color][color=#f60]i[/color][color=yellow]t[/color] [color=black]H[/color][color=black]e[/color][color=white]r[/color][color=purple]e[/color] 

[color=purple]H[/color][color=white]i[/color][color=purple]t[/color] [color=black]H[/color][color=green]e[/color][color=red]r[/color][color=blue]e[/color] 

[color=yellow]H[/color][color=green]i[/color][color=#f60]t[/color] [color=blue]H[/color][color=white]e[/color][color=green]r[/color][color=pink]e[/color] 
+0

'random.choice'更直接地解決了這個問題。 –

+0

使用選擇功能編輯答案。謝謝! – Ananth

0

嘗試這樣的:

import random 

#console color 
W = '\033[0m' # white (normal) 
R = '\033[31m' # red 
G = '\033[32m' # green 
O = '\033[33m' # orange 
B = '\033[34m' # blue 
P = '\033[35m' # purple 

my_color = [W, R, G, O, B, P] 

a = raw_input("Enter your text to be colourful: ") 
new_text ="" 
for x in a: 
    new_text += x + random.choice(my_color) 

print new_text + W 

enter image description here

所需輸出:

>>> import random 
>>> color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'] 
>>> new_text = "" 
>>> import random 
>>> for x in text: 
...  new_text += "[color={}]{}[/color]".format(random.choice(color), x) 
... 
>>> new_text 
'[color=#f60]h[/color][color=white]e[/color][color=blue]l[/color][color=#f60]l[/color][color=black]o[/color][color=white] [/color][color=purple]h[/color][color=white]o[/color][color=green]w[/color][color=pink] [/color][color=white]a[/color][color=white]r[/color][color=yellow]e[/color][color=red] [/color][color=#f60]y[/color][color=green]o[/color][color=red]u[/color]' 
0

PIP安裝Pygments來做,那就試試這個:

import random 
from pygments.console import codes 
string='some string here' 
print ''.join([random.choice(codes.values())+x+codes['reset'] for x in string])