python用多个键填充一个搁置对象/字典 [英] python populate a shelve object/dictionary with multiple keys
本文介绍了python用多个键填充一个搁置对象/字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
['我','去','到','工作']
['我','去','那里','经常']
['it','is'
['我','活','在','纽约']
['我','去','到','工作']
所以我们有这样的东西:
four_grams ['I'] ['go'] ['to'] ['work'] = 1
,并且任何新遇到的4克用其四个键填充,值为1,如果再次遇到,它的值会增加。
解决方案
你可以这样做:
import shelve
从集合import defaultdict
db = shelve.open('/ tmp / db')
克= [
['我','去','到','工作'],
['我','去','那里','经常'],
['it','is','nice','being'],
['I','live','in','NY'],
['I'
$ b(克):
path = db.get(gram [0],defaultdict(int))
def f(path,word):
如果不是路径中的单词:
path [word] = defaultdict(int)
返回路径[word]
reduce(f,gram [1:-1],path)[gram [-1]] + = 1
db [gram [0]] = path
打印db
db.close()
I have a list of 4-grams that I want to populate a dictionary object/shevle object with:
['I','go','to','work']
['I','go','there','often']
['it','is','nice','being']
['I','live','in','NY']
['I','go','to','work']
So that we have something like:
four_grams['I']['go']['to']['work']=1
and any newly encountered 4-gram is populated with its four keys, with the value 1, and its value is incremented if it is encountered again.
解决方案
You could do something like this:
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()
这篇关于python用多个键填充一个搁置对象/字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文