Can I find subject from Spacy Dependency tree using NLTK in python?
<p>I want to find the <strong>subject</strong> from a sentence using <code>Spacy</code>. The code below is working fine and giving a <strong>dependency tree</strong>.</p>

<pre><code>import spacy
from nltk import Tree

en_nlp = spacy.load('en')

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

def to_nltk_tree(node):
    if node.n_lefts + node.n_rights &gt; 0:
        return Tree(node.orth_, [to_nltk_tree(child) for child in node.children])
    else:
        return node.orth_


[to_nltk_tree(sent.root).pretty_print() for sent in doc.sents]
</code></pre>

<p><a href="http://i.stack.imgur.com/OhAFy.png" rel="nofollow"><img src="http://i.stack.imgur.com/OhAFy.png" alt="enter image description here"></a></p>

<p>From this dependency tree code, Can I find the <strong>subject</strong> of this sentence?</p>

<p>I'm not sure whether you want to write code using the nltk parse tree (see <a href="http://stackoverflow.com/questions/28618400/how-to-identify-the-subject-of-a-sentence">How to identify the subject of a sentence?</a> ). But, spacy also generates this with the 'nsubj' label of the word.dep_ property. </p>

<pre><code>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:det
quick:amod
brown:amod
fox:nsubj
jumps:ROOT
over:prep
the:det
lazy:amod
dog:pobj
</code></pre>

<p>Reminder that there could more complicated situations where there is more than one.</p>

<pre><code>&gt;&gt;&gt; doc2 = en_nlp(u'When we study hard, we usually do well.')
&gt;&gt;&gt; sentence2 = next(doc2.sents)
&gt;&gt;&gt; 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
</code></pre>

python nlp spacy