如何让每一个字符/行都打印成任意颜色? [英] How to make every character/line print in a random color?

查看:0
本文介绍了如何让每一个字符/行都打印成任意颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的愿望是让每个字符或行或任何你认为最适合ASCII的东西看起来都像。基本上我试过colorama,它只基于一种颜色。最好的方法是什么?

我所拥有的是

print("""


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




    """)

差不多就是这样。通过这个让我知道你的想法!

推荐答案

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

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

如果您想要彩色线条,只需进行简单的更改:

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

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

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

这提供了:

这篇关于如何让每一个字符/行都打印成任意颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆