still_learning
still_learning

Reputation: 806

Dependency parsing visualisation

How can I represent the following sentence:

txt1="The chef cooks the soup"

as follows:

enter image description here

I would like to visualise the sentence like shown in the image, i.e. as a tree/network. Any advice would be greatly appreciate. I am using nltk for word embedding.

Upvotes: 0

Views: 593

Answers (1)

Akshay Sehgal
Akshay Sehgal

Reputation: 19322

What you are looking for is Dependency Parsing in NLP. A parsing tree can be generated by multiple libraries, for example the image that you show is from Stanford NLP and you can find tons of tutorials on it. I prefer Spacy for majority of my NLP so here is a Spacy way of doing the same.

#!pip install -U spacy
#!python -m spacy download en
from nltk import Tree
import spacy
en_nlp = spacy.load('en')


def tok_format(tok):
    return "_".join([tok.orth_, tok.tag_, tok.dep_])


def to_nltk_tree(node):
    if node.n_lefts + node.n_rights > 0:
        return Tree(tok_format(node), [to_nltk_tree(child) for child in node.children])
    else:
        return tok_format(node)


command = "The chef cooks the soup"
en_doc = en_nlp(u'' + command) 

[to_nltk_tree(sent.root).pretty_print() for sent in en_doc.sents]
              cooks_VBZ_ROOT             
       _____________|_____________        
chef_NN_nsubj                soup_NN_dobj
      |                           |       
  The_DT_det                  the_DT_det 
command = "She sells sea shells on the sea shore"
en_doc = en_nlp(u'' + command) 

[to_nltk_tree(sent.root).pretty_print() for sent in en_doc.sents]
               sells_VBZ_ROOT                                         
       ______________|_________________________                        
      |              |                     on_IN_prep                 
      |              |                         |                       
      |       shells_NNS_dobj            shore_NN_pobj                
      |              |             ____________|______________         
She_PRP_nsubj sea_NN_compound the_DT_det               sea_NN_compound

Upvotes: 1

Related Questions