📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division1213import shelve14import sys1516from anagram_sets import all_anagrams, signature171819def store_anagrams(filename, anagram_map):20"""Stores the anagrams from a dictionary in a shelf.2122filename: string file name of shelf23anagram_map: dictionary that maps strings to list of anagrams24"""25shelf = shelve.open(filename, 'c')2627for word, word_list in anagram_map.items():28shelf[word] = word_list2930shelf.close()313233def read_anagrams(filename, word):34"""Looks up a word in a shelf and returns a list of its anagrams.3536filename: string file name of shelf37word: word to look up38"""39shelf = shelve.open(filename)40sig = signature(word)41try:42return shelf[sig]43except KeyError:44return []454647def main(script, command='make_db'):48if command == 'make_db':49anagram_map = all_anagrams('words.txt')50store_anagrams('anagrams.db', anagram_map)51else:52print(read_anagrams('anagrams.db', command))535455if __name__ == '__main__':56main(*sys.argv)57585960