Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96169
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
import shelve
15
import sys
16
17
from anagram_sets import all_anagrams, signature
18
19
20
def store_anagrams(filename, anagram_map):
21
"""Stores the anagrams from a dictionary in a shelf.
22
23
filename: string file name of shelf
24
anagram_map: dictionary that maps strings to list of anagrams
25
"""
26
shelf = shelve.open(filename, 'c')
27
28
for word, word_list in anagram_map.items():
29
shelf[word] = word_list
30
31
shelf.close()
32
33
34
def read_anagrams(filename, word):
35
"""Looks up a word in a shelf and returns a list of its anagrams.
36
37
filename: string file name of shelf
38
word: word to look up
39
"""
40
shelf = shelve.open(filename)
41
sig = signature(word)
42
try:
43
return shelf[sig]
44
except KeyError:
45
return []
46
47
48
def main(script, command='make_db'):
49
if command == 'make_db':
50
anagram_map = all_anagrams('words.txt')
51
store_anagrams('anagrams.db', anagram_map)
52
else:
53
print(read_anagrams('anagrams.db', command))
54
55
56
if __name__ == '__main__':
57
main(*sys.argv)
58
59
60