随机颜色文本生成

时间:2015-01-13 18:53:19

标签: python random

我正在尝试在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]

从我制作的列表中颜色应该是随机的。这有可能吗?

3 个答案:

答案 0 :(得分:2)

这对我有用:

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]

答案 1 :(得分:1)

pip install 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])

答案 2 :(得分: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]'