0

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.

Community
  • 1
  • 1
GokuShanth
  • 203
  • 3
  • 12

1 Answers1

2

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.

Tom Cornebize
  • 1,362
  • 15
  • 33
  • 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 06: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 09:47