Преобразование дерева NLTK в массив словарей - PullRequest
0 голосов
/ 17 апреля 2020

Я хотел бы преобразовать следующее дерево nltk в массив словарей:

(S
  I/PRP
  'll/MD
  have/VB
  (amount 1/CD)
  (meal pizza/NN)
  with/IN
  (ingredient bacon/NN)
  and/CC
  (amount 2/CD)
  (meal hamburgers/NNS)
  with/IN
  (ingredient cheese/NN))

[{'amount': '1', 'meal': 'pizza', 'ingredient': 'bacon'},
{'amount': '2', 'meal': 'hamburgers', 'ingredient': 'cheese'}]

Я создал следующий код для его получения:

comanda = [('I', 'PRP'), ("'ll", 'MD'), ('have', 'VB'), ('1', 'CD'), ('pizza', 'NN'), ('with', 'IN'), ('bacon', 'NN'), ('and', 'CC'), ('2', 'CD'), ('hamburgers', 'NNS'), ('with', 'IN'), ('cheese', 'NN')]

def IOB_pedido(menu):

    grammar = r"""
        meal:      {<NN|NNS><IN|NN>}       
                     }<IN>{                  
        ingredient: {<IN>?<NN|NNS>}
                     }<IN>{
        amount:    {<CD>}                 
                     {<DT>}
    """
    result = nltk.RegexpParser(grammar).parse(menu)
    iob_tags = tree2conlltags(result)
    tree = conlltags2tree(iob_tags)
    return tree
output = IOB_pedido(comanda)

def tree_to_dict(tree):
    tree_dict = {}
    for nodo in tree:
        if type(nodo) == tuple:
            continue
        salida = []
        key = nodo.label()
        value = nodo[0][0]
        tree_dict.update([(key, value)])
        salida.append((tree_dict))

    return salida

tree_to_dict(output)

Но только по любой причине de вторая часть показана, по какой причине я не получаю следующий вывод?

[{'amount': '1', 'meal': 'pizza', 'ingredient': 'bacon'},
    {'amount': '2', 'meal': 'hamburgers', 'ingredient': 'cheese'}]

1 Ответ

0 голосов
/ 20 апреля 2020

Извините, я имею в виду следующее:

[{'amount': '2', 'meal': 'hamburgers', 'ingredient': 'cheese'}]

и я хочу что-то вроде этого:

[{'amount': '1', 'meal': 'pizza', 'ingredient': 'bacon'},
 {'amount': '2', 'meal': 'hamburgers', 'ingredient': 'cheese'}]

Я не знаю, почему я получаю только секунду часть дерева входит в список словарей.

...