generating tag cloud in Python

Tag Clouds are an amazing way to emphasize on what is needed. Here, is a simple code snippet in Python that will generate tag cloud, on the basis of tags and their count provided.

The algorithm for generating tag cloud is used from http://en.wikipedia.org/wiki/Tag_cloud#Creation_of_a_tag_cloud

def generate_tag_cloud(tags, baseurl=’http://www.example.com/tag/’, fmax = 20):
“””Generates HTML of tag cloud.
Input params:
tags : A dictionary containing the key as the tag name, and
value as the count of times, it appears
ex: {‘tag1’: 2, ‘tag2’: 1, ‘tag3’: 45}
fmax : The maximum font size to display. pixel

http://en.wikipedia.org/wiki/Tag_cloud#Creation_of_a_tag_cloud
“””
size = lambda f_max, t_max, t_min, t_i : t_i > t_min and int(math.ceil((f_max*(t_i – t_min))/(t_max – t_min))) or 10

f_max = fmax
t_min = min(tags.values())
t_max = max(tags.values())
cloud = []

for tag in tags:
cloud.append({‘tag’: tag,
‘count’: tags.get(tag),
‘size’: size(f_max,t_max,t_min,tags.get(tag))})
s = []
for onetag in cloud:
s.append(‘%s
%(onetag.get(‘size’), baseurl+onetag.get(‘tag’), onetag.get(‘count’), tag ))
return ‘

‘ + ”.join(s) + ‘

# Assumes the data structure for tag as
# class Tag(object):
# def __init__(self, name, count, permalink):
# self.name = name
# self.count = count
# self.permalink = permalink
# And why would one have such a structure? Well, watch out for http://beamto.us
# source when it is released
#
def gen_tagcloud(tags):
“””Generates the dict for tag cloud based on the input provided
tags = [tag1, tag2, tag3]
“””
conf = ‘log’ # for logarithmic cloud, try ‘linear’ for linear
min_weight = min([x.count for x in tags])
max_weight = max([x.count for x in tags])
tag_cloud = []
if conf.get(‘ALGO’).lower().startswith(‘linear’):
for tag in tags:
w = (tag.count – min_weight)/(max_weight – min_weight)
f = conf.get(‘MIN-FONT’) + (conf.get(‘MAX-FONT’) – conf.get(‘MIN-FONT’) )*w
tag_cloud.append({‘tag’:tag, ‘count’:tag.count+1, ‘font’: f,
‘permalink’: tag.permalink})
if conf.get(‘ALGO’).lower().startswith(‘log’):
for tag in tags:
w = (math.log(tag.count or 1) – math.log(min_weight or 1))/\
(math.log(max_weight or 1) – math.log(min_weight or 1))
f = conf.get(‘MIN-FONT’) + (conf.get(‘MAX-FONT’) – conf.get(‘MIN-FONT’) )*w
tag_cloud.append({‘tag’:tag, ‘count’:tag.count + 1, ‘font’:f,
‘permalink’: tag.permalink})
return tag_cloud

You can tweak and create better versions. Also this is on the Python side, there could be a similar one for JavaScript as well, which generates tag clouds on the fly.