# unscramble.py # Steve Marschner (srm2) # February 18, 2013 """Anagram solver for lecture demo.""" import string import sys # On Unix systems, including Mac OS, this file, or /usr/dict/words, usually # holds all the words in an English dictionary, one word per line. #DICT_FILE = '/usr/share/dict/words' # But I am using another word list, from Kevin Atkinson's SCOWL (Spell Checker # Oriented Word Lists) project, see wordlist.sourceforge.net. DICT_FILE = 'scowl_utf-8.txt' def prep_line(line): """Prepare a line read from the word list file by removing the trailing newline and lowercasing it.""" return line.strip().lower() def sort_string(s): """Return a copy of s with the characters sorted in alphabetical order.""" x = list(s) x.sort() return ''.join(x) dictionary = map(prep_line, open(DICT_FILE).readlines()) sorted_dict = map(sort_string, dictionary) def unscramble(anagram): """Attempts to unscramble an anagram of an English word. If <anagram> contains an permutation of the letters in an English word, print the word. If not, print an error message. """ if sort_string(anagram) in sorted_dict: i = sorted_dict.index(sort_string(anagram)) print 'Your word is an anagram of "' + dictionary[i] + '"' else: print 'Your word is not an anagram of anything' if __name__ == '__main__': if len(sys.argv) == 2: unscramble(sys.argv[1]) else: print "Usage: python unscramble.py <word>"