標籤:utf-8 party proc and png 簡單 ace idt min
只使用Python的random庫,將已有資料產生HTML格式的標籤雲。思路就是根據同一單詞出現的次數多少,產生不同大小不同顏色單詞的資料的視圖。
比如以下格式的多條資料:
1Gaming1Skateboarding2Girl Friend3Surfing the Internet3TED talks4Reading4Writing5Facebook5Gaming6Gaming6Martial Arts7Partying7Playing Sport7Travel8Driving8Socializing with Friends9Eating9Procrastinating9Sleeping10Winning……
可製作成效果如下:
首先,將資料存在一個dict裡,鍵為單詞,值為出現的個數:
words = ‘‘for line in data: word = line.split(‘\t‘)[1] if word not in words: words[word] = 1 else: words[word] += 1
然後將製作HTML,將不同單詞設定成隨機的顏色,按單詞出現的頻率設定不同的字型大小。
html = ""for w, c in words.items(): color = ‘rgb(%s, %s, %s)‘ % (str(random.randint(0, 255)), str(random.randint(0, 255)), str(random.randint(0, 255))) fontsize = int(c * 0.1 + 10) html += ‘<span style=\"font-size:‘ + str(fontsize) + ‘px;color:‘ + color + ‘;float:left;\">‘ + w + ‘</span>‘# dump it to a filewith open(‘result.html‘, ‘wb‘) as f: f.write(bytes(html, ‘UTF-8‘))
到這裡,已經完成了!
使用Python自己實現簡單的資料視覺效果