How do I do dependency parsing in NLTK?

前端 未结 7 960
醉梦人生
醉梦人生 2020-11-29 20:53

Going through the NLTK book, it\'s not clear how to generate a dependency tree from a given sentence.

The relevant section of the book: sub-chapter on dependency gra

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 21:15

    A little late to the party, but I wanted to add some example code with SpaCy that gets you your desired output:

    import spacy
    nlp = spacy.load("en_core_web_sm")
    doc = nlp("I shot an elephant in my sleep")
    for token in doc:
        print("{2}({3}-{6}, {0}-{5})".format(token.text, token.tag_, token.dep_, token.head.text, token.head.tag_, token.i+1, token.head.i+1))
    

    And here's the output, very similar to your desired output:

    nsubj(shot-2, I-1)
    ROOT(shot-2, shot-2)
    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)
    

    Hope that helps!

提交回复
热议问题