[Tutor] Random Words.

Tesla Coil tescoil@irtc.net
Sun, 03 Jun 2001 17:13:47 -0500


Way to read the file more efficiently if it were
larger? (/usr/share/dict/words has 45,424 entries;
I also have /usr/dict/words with 79,339 entries,
and /usr/dict/words.ott with 172,822).  

Where would be preferable to filter out undesired 
words?  Remove them from the list before choosing,
or, reject them if chosen and replace them?  I'm 
inclined toward the latter, but wonder if that's
best when there's fair chance of rejection, say,
refusing len(words) <=3 and >=9.

And just interested in any different approach...

#!/usr/bin/env python
# randword.py -- Quick and Dirty  
# return a list of random words.
import random

def readfile(lexfile):
    file = open(lexfile)
    lexlist = file.readlines()
    file.close()
    return lexlist

def choosewords(lexlist):
    randwords = []
    entries = len(lexlist)
    for iteration in range(20):
    	word = random.randint(0, entries)
	randwords.append(wordlist[word])
    return randwords	

wordsource = '/usr/share/dict/words'
wordlist = readfile(wordsource)
randlist = choosewords(wordlist)
for word in randlist: print word,