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

标签 python dictionary n-gram shelve

我有一个 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()

关于python 用多个键填充一个搁置对象/字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20786895/

相关文章:

nlp - 字节 vs 字符 vs 单词 - n-gram 的粒度是什么?

elasticsearch - Elasticsearch 6.8 match_phrase搜索N元语法分词器效果不佳

python - Mapper Mapper|用户|用户无法组装映射表的任何主键列 'users'

python - 使用 Python 脚本在 MS SQL 数据库中创建表时出现问题

Python 字典包含列表/设置为值。如何向其中添加/添加新元素?

Javascript 相当于 Python 的 dict.setdefault 吗?

python - 在字典理解中订阅 locals() 失败并出现 KeyError

python - 如何从句子中提取字符ngram? - Python

python - 字符串到 MySQL 中的 DATETIME

python - 什么是 "@"在 Python 函数之上的装饰器?