Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In nltk tree how can I access a parent from a child?

Tags:

python

nltk

Suppose I had a variable that holds a tree of nltk tree class. Is there any function like parent() or something that returns the parent of the node?

like image 377
Nikhil Vandanapu Avatar asked Dec 19 '22 05:12

Nikhil Vandanapu


1 Answers

You need a different data structure: A tree whose nodes contain pointers to their parent. The NLTK now provides the type nltk.tree.ParentedTree (as @Gerhard already pointed out). But the NLTK corpora and tools generate plain Tree objects, so you need to convert. If you have a variable mytree that contains your tree, convert it like this:

from nltk.tree import ParentedTree
newtree = ParentedTree.convert(mytree)

The nodes of the new tree will have a parent() method that you can use to navigate up the tree.

like image 105
alexis Avatar answered Dec 22 '22 00:12

alexis