On Sun, Feb 03, 2008 at 04:35:08PM -0500, Kent Johnson made several helpful suggestions:
Thanks! That cleaned up a lot. However, I couldn't figure out a way to do random.choice(word_hash[(w1, w2)]) on a dict with set-type values. The closest I could get was word_hash[(w1, w2)].pop(), but then I need to add a few lines to put the value back into the set afterwards. Is there a way to randomly lookup a value in a set without removing it from the set? I had better success with collections.defaultdict(list), as pasted below. Cheers, Tyler #! /usr/bin/python2.5 import sys, random, collections word_max = 1000 # Read in file infile = open(sys.argv[1], 'r') ifstring = infile.read() # break file into words iflist = ifstring.split() # build hash of form (prefix1, prefix2): [word] word_hash = collections.defaultdict(list) for i in range(len(iflist) - 2): tk = tuple(iflist[i:i+2]) tv = iflist[i+2] if tv not in word_hash[tk]: word_hash[tk].append(tv) word_hash[(iflist[-2], iflist[-1])].append('\n') # output first two words w1, w2 = iflist[0:2] print w1, w2, # generate new words from hash for word_num in range(word_max): w1, w2 = w2, random.choice(word_hash[(w1, w2)]) print w2, if w2 == '\n': break _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor