对不起,如果这真的很糟糕,我是python的新人,所以请原谅我的无知。我试图创建一个方法,该方法可以将一个单词作为参数,并使用带有彩虹色的HTML字体标记返回该单词。
def rainbow(word):
length = len(word)
#set rgb values
r = 255 #rgb value set to red by default
g = 0
b = 0
sub = int(765/length)
counter = 0
string = ""
for x in range(0, length):
letter = word[counter]
s = "<font color = #%02X%02X%02X>%s</font>" % (r, g, b, letter)
string = string+s
counter+=1
if (r == 255) and (g >= 0) and (b == 0):
g = g+sub
if g > 255: g = 255
if (r > 0) and (g == 255) and (b == 0):
r = r-sub
if r<0: r = 0
if (r == 0) and (g == 255) and (b == 0): #b is not increasing
b = b+sub
if b>255: b = 255
if (r == 0) and (g > 0) and (b == 255): #this one doesn't work either
g = g-sub
if g<0: g = 0
if (r <255) and (g == 0) and (b == 255): #or this one
r = r+sub
if r>255: r = 255
return string
是的,我知道它很糟糕,就像我说的,我是新的。但是,当执行此脚本时,&#39; b&#39;价值永远不会增加。因此输出总是返回正确的彩虹直到绿色。请告诉我我做错了什么!
答案 0 :(得分:1)
使用HSV color space获取彩虹颜色可能更容易。然后colorsys.hsv_to_rgb()
function允许从HSV转换为RGB:
import html
from colorsys import hsv_to_rgb
def html_rainbow(text):
n = len(text)
L = []
for i, c in enumerate(text):
hue = i / n
r, g, b = [int(f*255 + .5) for f in hsv_to_rgb(hue, 1, 1)]
L.append('<font color=#%02X%02X%02X>%s</font>' % (
r, g, b, html.escape(c, quote=False)))
return ''.join(L)
测试脚本:
#!/usr/bin/env python3
"""Usage: %(prog)s <text>"""
import sys
import tempfile
import time
import webbrowser
def open_in_browser(html):
with tempfile.NamedTemporaryFile("w", suffix='.html') as file:
file.write(html)
file.flush()
webbrowser.open(file.name)
time.sleep(60) # give the browser a minute to open before
# deleting the file
if len(sys.argv) < 2:
sys.exit(__doc__ % dict(prog=sys.argv[0]))
open_in_browser(html_rainbow(sys.argv[1]))
示例:
$ python3 html_rainbow.py "rainbow & rainbow"
答案 1 :(得分:0)
我不确定你准备做什么,但是那条条件似乎非常不优雅,所以我跳过它并写下了这个解决方案:
def rainbow(word):
import math
wordLen = len(word)
freq = (2 * math.pi) / wordLen
amplitude = 255 / 2
center = 255 / 2
line = ''
for i in range(wordLen):
currChar = word[i]
#G and B should be shifted to all three channels are not the same color
gShift = math.pi * 2 / 3
bShift = math.pi * 4 / 3
r = math.sin(freq * i) * amplitude + center
g = math.sin(freq * i + gShift) * amplitude + center
b = math.sin(freq * i + bShift) * amplitude + center
line += '<font color="rgb({},{},{})">{}</font>'.format(r, g, b, currChar)
return line
if __name__ == '__main__':
print rainbow('pooooooooooooooooooooooooooooooooooooooooooooooooop')
在使用每个字符打印标签之前,它使用正弦波¹为每个通道产生0到255之间的起伏值。
这是无关紧要的,但请注意我使用的是字符串format()方法,而不是您在代码中使用的弃用方法。
还有一个原型:至少要避免命名一个变量'string',因为很容易将变量'string'与Python的字符串模块混淆,尽管你很可能不会很快导入它。
¹This似乎是了解正弦波的好地方