Python 版的彩紅文字 (Rainbow Text)


剛用 PHP 寫了個相同的東西.
現在又心血來潮用 Python 試刀.
果然 Python 比起 PHP 代碼上簡單得很.
不過可能 Python 3.0 上會有問題,因為不支援 u”xxx” 的表示方法?
不過目前都在用 2.x 版本.日後再算吧.

22:30: 增加多一種方法,應該可支持 Python 3.0 吧 (沒實測)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/python
# -*- coding: utf8 -*-

"""
Author : Zeuxis Lo
P-Date : 7/7/2009 22:10
Version: 0.1.0707
"""

print "content-type: text/html; charset=utf-8"
print

class Rainbow:
def __init__(self):
pass

def getText(self, text):
ret = ''
colors = [
'ff00ff', 'ff00cc', 'ff0099', 'ff0066', 'ff0033', 'ff0000', 'ff3300', 'ff6600', 'ff9900', 'ffcc00', 'ffff00',
'ccff00', '99ff00', '66ff00', '33ff00', '00ff00', '00ff33', '00ff66', '00ff99', '00ffcc', '00ffff', '00ccff',
'0099ff', '0066ff', '0033ff', '0000ff', '3300ff', '6600ff', '9900ff', 'cc00ff'
]

i = 0
textLength = len(text)

while(i < textLength):
for color in colors:
if (i < textLength):
txt = text[i]
ret += "<span style='color:#%s'>%s</span>" % (color, txt)
i = i + 1
return ret

if __name__ == "__main__":
print Rainbow().getText(u"這是一個系統上的測試").encode("utf8")
print "<br />"
print Rainbow().getText("這是一個系統上的測試".decode("utf8")).encode("utf8")