gpt4 book ai didi

python - 如何以随机颜色打印每个字符/行?

转载 作者:行者123 更新时间:2023-11-28 21:03:30 24 4
gpt4 key购买 nike

我的愿望是让每个字符或行或任何​​你认为最适合 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))

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

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

关于python - 如何以随机颜色打印每个字符/行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46425645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com