Python заполнить объект / словарь полки несколькими ключами

У меня есть список из 4 граммов, которые я хочу, чтобы заполнить объект словаря / объекта 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-грамм заполняется его четырьмя ключами со значением 1, и его значение увеличивается, если оно встречается снова.

2 ответа

Решение

Вы могли бы сделать что-то вроде этого:

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()

Вы можете просто создать вспомогательный метод, который будет вставлять элементы во вложенный словарь по одному, каждый раз проверяя, существует ли уже нужный словарь или нет:

dict = {}
def insert(fourgram):
    d = dict    # reference
    for el in fourgram[0:-1]:       # elements 1-3 if fourgram has 4 elements
        if el not in d: d[el] = {}  # create new, empty dict
        d = d[el]                   # move into next level dict

    if fourgram[-1] in d: d[fourgram[-1]] += 1  # increment existing, or...
    else: d[fourgram[-1]] = 1                   # ...create as 1 first time

Вы можете заполнить его своим набором данных как:

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

после чего вы можете индексировать в dict по желанию:

print( dict['I']['go']['to']['work'] );     # prints 2
print( dict['I']['go']['there']['often'] ); # prints 1
print( dict['it']['is']['nice']['being'] ); # prints 1
print( dict['I']['live']['in']['NY'] );     # prints 1
Другие вопросы по тегам