""" Main module for the keypad entry problem. Usage: $ python keypad.py > 0405683056830687420 > ... > ^D $ Author: Rodney Topor Date: November 2007 Last updated: 1 August 2011 """ import string from re import split from sys import stdin from keypad_dict import add_word, get_words def read_dictionary(): """Read a sequence of words from file word.list into a dictionary.""" try: file = open('word.list', 'r') except: print "Cannot open file word.list. Exiting." return False for line in file: for word in line.split(): add_word(word) file.close() return True def read_messages(): """ Read, translate and print a sequence of numeric messages from stdin. """ prompt = "> " print prompt, line = stdin.readline() while (line != ""): digitsSeq = split('0+', line.strip('0\n')) print " ".join([ format(get_words(digits)) for digits in digitsSeq ]) print prompt, line = stdin.readline() def format(words): """Parenthesise word lists of length greater than 1.""" if (len(words) == 1): return words[0] else: return "(" + "|".join(words) + ")" if __name__ == "__main__": if (read_dictionary()): read_messages()