#!/usr/local/bin/python import string, sys, os, random, time # seed random number generator random.seed(os.getpid() * time.time()) def pickone(choices): """Select a random item from a list""" return choices[random.randrange(len(choices))].split() def find_key(dict, wordlist): """Return the index of the first word in wordlist that is a key in dict""" for i in range(len(wordlist)): if dict.has_key(wordlist[i]): return i return None def generate_phrase(words): """Recursively process a list of words, expanding the dictionary keys into randomly-selected replacement phrases""" if len(words) == 0: return [] i = find_key(repl, words) try: left = words[:i] choices = repl[words[i]] right = words[i+1:] return left + generate_phrase(pickone(choices) + right) except: # it didn't work return words def load_data(filename="/usr/home/each/python/foods"): global sentence, repl data = open(filename).read().splitlines() sentence = data.pop(0) repl = {} for line in data: line = line.split(":") for i in range(len(line)): line[i] = line[i].strip() # strip whitespace repl[line.pop(0)] = line # store replacement phrases in dictionary # CGI/HTML helper functions def printContentType(type="text/html"): print "Content-type:", type + "\n" def printDocType(fp=sys.stdout): fp.write('\n') def printHeaders(title="unknown", fp=sys.stdout): fp.write("\n") fp.write(""+title+"\n") fp.write("\n") fp.write('\n') def startList(header=None, fp=sys.stdout): if header: fp.write("

" + header + ":

\n") fp.write("") def printFooter(fp=sys.stdout): fp.write("\n") # # main # # load data file load_data() # generate HTML printContentType() printHeaders("Potluck menu") startList("This week's potluck will feature") for i in range(5): food = string.join(generate_phrase(sentence.split())) bulletItem(food[0].upper() + food[1:]) endList() printFooter()