Typed Dependency Parsing in NLTK Python


Typed Dependency Parsing in NLTK Python



I have a sentence


"I shot an elephant in my sleep"



The typed dependency of the sentence is


nsubj(shot-2, I-1)
det(elephant-4, an-3)
dobj(shot-2, elephant-4)
prep(shot-2, in-5)
poss(sleep-7, my-6)
pobj(in-5, sleep-7)



How do I get the typed dependency using Stanford Parser (or any parser) using NLTK (preferably, but anthing is fine) in Python ?



Note - I know it is very similar to this question. But no good answers exist.




1 Answer
1



There exists a python wrapper for the Stanford parser, you can get it here.



It will give you the dependency tree of your sentence.



EDIT:



I assume here that you launched a server as said here. I also assume that you have installed jsonrpclib.



The following code will produce what you want:


import json
import jsonrpclib

class StanfordNLP:
def __init__(self, port_number=8080):
self.server = jsonrpclib.Server("http://localhost:%d" % port_number)

def parse(self, text):
return json.loads(self.server.parse(text))

nlp = StanfordNLP()
sentence = 'I shot an elephant in my sleep'
result = nlp.parse(sentence)
result['sentences'][0]['indexeddependencies']

>>>
['root', 'ROOT-0', 'shot-2']
['nsubj', 'shot-2', 'I-1']
['det', 'elephant-4', 'an-3']
['dobj', 'shot-2', 'elephant-4']
['poss', 'sleep-7', 'my-6']
['prep_in', 'shot-2', 'sleep-7']



EDIT2:



Now, the Stanford parser has an HTTP API. Thus, the python wrapper is not necessary anymore.





It works. But the output it gives is not the same as the one in the example in documentation. How do I correct that ?
– GokuShanth
Mar 22 '15 at 6:47






I edited my answer to give you more details. The result is not exactly the same as yours, but I think it is close enough.
– Tom Cornebize
Mar 22 '15 at 9:47






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages