Skip to main content
 首页 » 编程设计

python 用多个键填充一个搁置对象/字典

2024年11月01日8itcoder

我有一个 4-gram 列表,我想用它来填充字典对象/shevle 对象:

['I','go','to','work'] 
['I','go','there','often'] 
['it','is','nice','being'] 
['I','live','in','NY'] 
['I','go','to','work'] 

所以我们有这样的东西:

four_grams['I']['go']['to']['work']=1 

并且任何新遇到的 4-gram 都用它的四个键填充,值为 1,如果再次遇到它,它的值会递增。

请您参考如下方法:

你可以这样做:

import shelve 
 
from collections import defaultdict 
 
db = shelve.open('/tmp/db') 
 
grams = [ 
    ['I','go','to','work'], 
    ['I','go','there','often'], 
    ['it','is','nice','being'], 
    ['I','live','in','NY'], 
    ['I','go','to','work'], 
] 
 
for gram in grams: 
    path = db.get(gram[0], defaultdict(int)) 
 
    def f(path, word): 
        if not word in path: 
            path[word] = defaultdict(int) 
        return path[word] 
    reduce(f, gram[1:-1], path)[gram[-1]] += 1 
 
    db[gram[0]] = path 
 
print db 
 
db.close()