How to get parent node in Stanford's JavaNLP?
-
01-10-2019 - |
Question
Suppose I have such chunk of a sentence:
(NP
(NP (DT A) (JJ single) (NN page))
(PP (IN in)
(NP (DT a) (NN wiki) (NN website))))
At a certain moment of time I have a reference to (JJ single)
and I want to get the NP
node binding A single page
. If I get it right, that NP
is the parent of the node, A
and page
are its siblings and it has no children (?). When I try to use the .parent()
method of a tree, I always get null. The API says that's because the implementation doesn't know how to determine the parent node. Another method of interest is .ancestor(int height, Tree root)
, but I don't know how to get the root of the node. In both cases, since the parser knows how to indent and group trees, it must know the "parent" tree, right? How can I get it? Thanks
Solution
It looks like the Tree
itself will never return the parent of the node, since it's hardcoded in the Tree
sources. Meanwhile TreeGraphNode
overrides that method and works well. Changing a Tree to a TreeGraphNode is as easy as
TreeGraphNode sentence = new TreeGraph(tree).root();
OTHER TIPS
If you keep a reference to the root of the tree, then you can use method parent(Tree root)
to get the parent of any node in the tree. Assume that the tree root is referred to as root
, and that the JJ node is referred to as jjTree
, then jjTree.parent(root)
will return the parent NP node.