Древовидная структура от парсера Stanford CoreNLP - PullRequest
0 голосов
/ 01 сентября 2018

Я пытаюсь запустить анализатор StanfordCoreNLP, и у меня есть следующий код:

from pycorenlp import StanfordCoreNLP

nlp = StanfordCoreNLP('http://localhost:9000')

def depparse(text):
    parsed=""
    output = nlp.annotate(text, properties={
      'annotators': 'depparse',
      'outputFormat': 'json'
      })

    for i in output["sentences"]:
        for j in i["basicDependencies"]:
            parsed=parsed+str(j["dep"]+'('+ j["governorGloss"]+' ')+str(j["dependentGloss"]+')'+' ')
        return parsed
text='I shot an elephant in my sleep'
depparse(text)

Это дает мне вывод как: 'ROOT(ROOT shot) nsubj(shot I) det(elephant an) dobj(shot elephant) case(sleep in) nmod:poss(sleep my) nmod(shot sleep) '

Чтобы преобразовать отношения в дерево, я столкнулся с одной записью в стеке потока Формат дерева разбора Stanford NLP . Однако вывод синтаксического анализатора находится в «разборе (в дереве) в скобках». Следовательно, я не уверен, как я могу достичь этого. Я также попытался изменить формат вывода, но он выдает ошибку.

Я также нашел Python - сгенерировал словарь (дерево) из списка кортежей и реализовал

    list_of_tuples = [('ROOT','ROOT', 'shot'),('nsubj','shot', 'I'),('det','elephant', 'an'),('dobj','shot', 'elephant'),('case','sleep', 'in'),('nmod:poss','sleep', 'my'),('nmod','shot', 'sleep')]

nodes={}

for i in list_of_tuples:
    rel,parent,child=i
    nodes[child]={'Name':child,'Relationship':rel}

forest=[]

for i in list_of_tuples:
    rel,parent,child=i
    node=nodes[child]

    if parent=='ROOT':# this should be the Root Node
            forest.append(node)
    else:
        parent=nodes[parent]
        if not 'children' in parent:
            parent['children']=[]
        children=parent['children']
        children.append(node)

print forest

Я получил следующий вывод [{'Name': 'shot', 'Relationship': 'ROOT', 'children': [{'Name': 'I', 'Relationship': 'nsubj'}, {'Name': 'elephant', 'Relationship': 'dobj', 'children': [{'Name': 'an', 'Relationship': 'det'}]}, {'Name': 'sleep', 'Relationship': 'nmod', 'children': [{'Name': 'in', 'Relationship': 'case'}, {'Name': 'my', 'Relationship': 'nmod:poss'}]}]}]

1 Ответ

0 голосов
/ 11 сентября 2018

Действительно немного не по теме (на самом деле это не ответ на ваш первоначальный вопрос, а на ваш последний комментарий). Размещение его в качестве ответа, потому что код не очень хорошо вписывается в комментарий. Но просто слегка изменив функцию depparse, вы можете получить ее в нужном формате:

def depparse(text):
parsed=""
output = nlp.annotate(text, properties={
  'annotators': 'depparse',
  'outputFormat': 'json'
  })
for i in output['sentences']: # not sure if there can be multiple items here. If so, it just returns the first one currently.
    return [tuple((dep['dep'], dep['governorGloss'], dep['dependentGloss'])) for dep in i['basicDependencies']]
...