forked from AllenDowney/ThinkPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anagram_db.py
55 lines (37 loc) · 1.11 KB
/
anagram_db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""This module contains code from
Think Python by Allen B. Downey
http://thinkpython.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import shelve
import sys
from anagram_sets import *
def store_anagrams(filename, ad):
"""Stores the anagrams in ad in a shelf.
filename: string file name of shelf
ad: dictionary that maps strings to list of anagrams
"""
shelf = shelve.open(filename, 'c')
for word, word_list in ad.iteritems():
shelf[word] = word_list
shelf.close()
def read_anagrams(filename, word):
"""Looks up a word in a shelf and returns a list of its anagrams.
filename: string file name of shelf
word: word to look up
"""
shelf = shelve.open(filename)
sig = signature(word)
try:
return shelf[sig]
except KeyError:
return []
def main(name, command='store'):
if command == 'store':
ad = all_anagrams('words.txt')
store_anagrams('anagrams.db', ad)
else:
print read_anagrams('anagrams.db', command)
if __name__ == '__main__':
main(*sys.argv)