简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM