
DBM 模組
|
393
一個 shelving 的例子
下列的範例所處理的任務與前面的
json
和
pickle
範例相同,但使用
shelve
來續存
(filename,linenumber)
對組所成的串列:
import collections, fileinput, shelve
word_pos = collections.defaultdict(list)
for line in fileinput.input():
pos = fileinput.filename(), fileinput.filelineno()
for word in line.split():
word_pos[word].append(pos)
sh_out = shelve.open('indexfiles','n')
sh_out.update(word_pos)
sh_out.close()
我們必須使用
shelve
來讀回儲存在類 DBM 檔案
indexfiles
中的資料,如
下列範例中所示:
import sys, shelve, linecache
sh_in = shelve.open('indexfiles')
for word in sys.argv[1:]:
if word not in sh_in:
print('Word {!r} not found in index file'.format(word),
file=sys.stderr)
continue
places = sh_in[word] ...