import string import whrandom class WordList: """Read in a list of words and divide according to length. Only words with only lower case letters are used.""" def __init__(self, filename): self.words = {} trans = string.maketrans('', '') f = open(filename) while 1: line = f.readline() if not line: break word = string.strip(line) # Delete all lower case characters and ignore # the word if any bad characters remain bad = string.translate(word, trans, string.lowercase) if len(bad) > 0: continue # Must be a good word. Add it to our list of # words of the same length. If this word is the # first one of its length, the exception case will # used. try: self.words[len(word)].append(word) except KeyError: self.words[len(word)] = [ word ] f.close() def selectWord(self, length=-1): """Select a word of given length. If no length is given, a random length is selected. If no words of the given length is available, a KeyError is raised.""" if length < 0: length = whrandom.choice(self.words.keys()) return whrandom.choice(self.words[length]) class BigWordList(WordList): """List of big (>7 characters) words.""" def selectWord(self): """Select a big word.""" keys = filter(lambda length: length > 7, self.words.keys()) return WordList.selectWord(self, whrandom.choice(keys)) if __name__ == '__main__': wl = WordList('words') print wl.selectWord() print wl.selectWord(1) print wl.selectWord(3) print wl.selectWord(5) print wl.selectWord(7)