Skip to content Skip to sidebar Skip to footer

Can I Find Subject From Spacy Dependency Tree Using Nltk In Python?

I want to find the subject from a sentence using Spacy. The code below is working fine and giving a dependency tree. import spacy from nltk import Tree en_nlp = spacy.load('en')

Solution 1:

I'm not sure whether you want to write code using the nltk parse tree (see How to identify the subject of a sentence? ). But, spacy also generates this with the 'nsubj' label of the word.dep_ property.

import spacy
from nltk import Tree

en_nlp = spacy.load('en')

doc = en_nlp("The quick brown fox jumps over the lazy dog.")

sentence = next(doc.sents) 
for word in sentence:
...     print "%s:%s" % (word,word.dep_)
... 
The:detquick:amodbrown:amodfox:nsubjjumps:ROOTover:prepthe:detlazy:amoddog:pobj

Reminder that there could more complicated situations where there is more than one.

>>>doc2 = en_nlp(u'When we study hard, we usually do well.')>>>sentence2 = next(doc2.sents)>>>for word in sentence2:...print"%s:%s" %(word,word.dep_)... 
When:advmod
we:nsubj
study:advcl
hard:advmod
,:punct
we:nsubj
usually:advmod
do:ROOT
well:advmod
.:punct

Solution 2:

Same with leavesof3, I prefer to use spaCy for this kind of purpose. It has better visualization, i.e.

enter image description here

the subject will be the word or phrase (if you use noun chunking) with the dependency property "nsubj" or "normal subject"

You can access displaCy (spaCy visualization) demo here

Solution 3:

Try this:

import spacy
importen_core_web_smnlp= spacy.load('en_core_web_sm')
sent = "I need to be able to log into the Equitable siteI tried my username and password from the AXA Equitable site which worked fine yesterday but it won't allow me to log in and when I try to change my password it says my answer is incorrect for the secret question I just need to be able to log into the Equitable site"
nlp_doc=nlp(sent)
subject = [tok for tok in nlp_doc if(tok.dep_ == "nsubj") ]
print(subject)

Post a Comment for "Can I Find Subject From Spacy Dependency Tree Using Nltk In Python?"