Python-使每个字符/行随机进行彩色打印吗?

WeI*_*his 2 python ascii colors

我的愿望是使每个字符或每行或任何您认为可能看起来最适合ASCII的东西。基本上我已经尝试过,colorma并且它仅基于一种颜色。所以我在这里,问你们最好的方法是什么。我有的是

    print("""   


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




    """)
Run Code Online (Sandbox Code Playgroud)

就是这样。通过这个让我知道您的想法!

jme*_*jme 7

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))
Run Code Online (Sandbox Code Playgroud)

这将以不同的颜色打印每个字符:

颜色字符

如果您要使用彩色线条,这是一个简单的更改:

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

在此处输入图片说明

您可以根据需要定制颜色列表。例如,如果要删除可能与终端背景类似的颜色(黑色,白色等),则可以编写:

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))
Run Code Online (Sandbox Code Playgroud)

这使:

在此处输入图片说明