[Tutor] newbie code review please!

Tyler Smith tyler.smith at mail.mcgill.ca
Sun Feb 3 21:30:49 CET 2008


Hi,

I'm a middling amateur coder in C and elisp, trying to wrap my head around
python syntax. I've implemented the code for the markov chain random
text generator from Kernighan and Pike's "The practice of
programming", and I'd appreciate any tips on how to make it more
pythonic.

The code appears to work as intended. It reads a file, breaks the text
into a list of individual words. It then builds a hash table in the
form of: 

(prefix-word-1, prefix-word-2):[list-of-possible-following-words]

It finishes by using the hash table to generate a nonsensical, and
occasionally amusing bit of text based on the input.

Any comments welcome!

Thanks,

Tyler

#! /usr/bin/python

import sys, random

word_max = 1000

# Read in file
infile = open(sys.argv[1], 'r')
ifstring = infile.read()

# break file into words
iflist = ifstring.replace('\n', ' ').split()

# build hash of form (prefix1, prefix2): [word]
word_hash = {}
for i in range(len(iflist) - 2):
    pr1 = iflist[i]
    pr2 = iflist[i+1]
    tv = iflist[i+2]
    tk = (pr1, pr2)
    if word_hash.has_key(tk) and tv not in word_hash[tk]:
            word_hash[tk].append(tv)
    else:
        word_hash[tk] = [tv]

if word_hash.has_key((iflist[-2], iflist[-1])):
    word_hash[(iflist[-2], iflist[-1])].append('\n')
else:
    word_hash[(iflist[-2], iflist[-1])] = ['\n']        

# output first two words
w1, w2 = iflist[0:2]
print w1, w2,

# generate new words from hash
word_num = 0
while w2 <> '\n' and word_num < word_max:
    w1, w2 = w2, random.choice(word_hash[(w1, w2)])
    print w2,
    word_num += 1




More information about the Tutor mailing list