## FILE: html_tag_cloud.py ## AUTHOR: Eugene Wallingford ## DATE: 2014/12/06 ## COMMENT: These utility functions can be used to create tag clouds. ## at different average paces ## ## HISTORY: These functions originally appear in The Programming Historian ## http://niche.uwo.ca/programming-historian/index.php/Tag_clouds ## ## They were adapted by the authors of our text, The Practice of ## Computing Using Python, primarily to update them to Python 3. ## ## I modified them for naming convention, consistency, and ## personal style. ## ## USAGE: See a sample usage at the bottom. If you un-comment that code, ## it uses each of the functions to take a dictionary of word/count ## and produce a web page with a tag cloud. import string import datetime HTML_BIG = 96 # the largest font size produced HTML_LITTLE = 14 # the smallest font size produced def make_html_word(word, count, high, low): '''Make an HTML tag containing the word with a font size determined by the word count. The font size is scaled between HTML_BIG and HTML_LITTLE. high and low represent the highest and lowest word counts in the document. ''' ratio = (count-low) / float(high-low) fontsize = (ratio * HTML_BIG) + ((1-ratio) * HTML_LITTLE) fontsize = int(fontsize) word_str = '%s ' return word_str % (str(fontsize), word) def make_html_box(body): '''Make an HTML tag containing a string in a box. ''' box_str = '''
%s
''' return box_str % (body) def print_html_file(body, title): '''Create a standard HTML page with titles, header, and metadata. The page is written to a file named is [ title.html ]. ''' template = ''' %s

%s

%s
Last modified: %s ''' filename = title+'.html' time_now = datetime.datetime.now().ctime() the_str = template % (title, title, body, time_now) output = open(filename, 'w') output.write(the_str) output.close() # Sample usage # #pairs = [('hi', 5), ('there', 6), ('mom', 10), ('fred', 2), ('bill' ,20)] #high_count = 20 #low_count = 2 #body = '' # #for word, count in pairs: # body = body + make_html_word(word, count, high_count, low_count) # #box = make_html_box(body) #print_html_file(box, 'test_file')