Reputation: 352
I am trying to run StanfordCoreNLP parser and I have the following code:
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)
This gives me output as:
'ROOT(ROOT shot) nsubj(shot I) det(elephant an) dobj(shot elephant) case(sleep in) nmod:poss(sleep my) nmod(shot sleep) '
To convert the relationships into tree, I am encountered one stackoverflow post Stanford NLP parse tree format. However, the output of the parser is in "bracketed parse (tree)". Hence, I am not sure how can I achieve it. I tried changing the outputformat as well but it gives an error.
I also found Python - Generate a dictionary(tree) from a list of tuples and implemented
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
I got the following output [{'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'}]}]}]
Upvotes: 0
Views: 1674
Reputation: 1281
A bit off-topic indeed (this is not really an answer to your original question, but to your last comment). Posting it as an answer because the code wouldn't really fit nicely into a comment. But by just changing your depparse function slightly, you can get it in the desired format:
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']]
Upvotes: 0