I would like to get the parent and child nodes of a node in an nltk tree. I have seen this answer here but I couldn't manage to fit it to my purposes.
For example, having this tree:
ROOT
|
S
_______|______________
| VP |
| ___|____ |
NP | ADJP |
| | ____|____ |
PRP VBZ RB JJ .
| | | | |
It is so nice .
I have this code taken and modified from other answers that gives some information but is not quite what I want.
ptree = ParentedTree.fromstring('(ROOT (S (NP (PRP It)) \
(VP (VBZ is) (ADJP (RB so) (JJ nice))) (. .)))')
leaf_values = ptree.leaves()
ptree.pretty_print()
if 'nice' in leaf_values:
leaf_index = leaf_values.index('nice')
print(leaf_index)
tree_location = ptree.leaf_treeposition(leaf_index)
print(tree_location)
print(ptree[tree_location])
print(tree_location[:-1])
print(ptree[tree_location[:-1]])
print(tree_location[:-2])
print(ptree[tree_location[:-2]])
3
(0, 1, 1, 1, 0)
nice
(0, 1, 1, 1)
(JJ nice)
(0, 1, 1)
(ADJP (RB so) (JJ nice))
I would like to implement something like the following. Assume I have the position/node 'nice'. I would like to make a function so that I get the position of 'JJ' when I enter the position of 'nice' as a parameter. Like get_parent(positionOf('nice')) returns positionOf('JJ'). And then I can do get_parent(positionOf('JJ')) and it returns positionOf('ADJP'), etc.
I would also like to get the childs of a node, for example, if I have get_childs(positionOf('ADJP')) it should return position('RB') and positionOf('JJ').
Does someone know how could I implement that? Could you provide a small example?