Stanford Parser:如何获得C&C的父母的道路--->根?

时间:2016-03-23 16:11:51

标签: java algorithm stanford-nlp

这是Stanford Parser的图片

This is a picture of Stanford Parser

我有一棵Stanford Parser的树作为照片。我想得到C' parent的路径 - >根。示例:路径"但"' parent - > root = CC S Root,或" it"父母 - > root:PRP NP VP VP S S root 。但我不知道该怎么做。我使用Stanford Parser来解析语句。

        statement = "I have a dog , but I don't like it"
        Annotation document = new Annotation(statement);
        pipeline.annotate(document);
        List<CoreMap> sentences = document
            .get(CoreAnnotations.SentencesAnnotation.class);

         for (CoreMap sentence : sentences) {
        Tree tree = sentence.get(TreeCoreAnnotations.TreeAnnotation.class);
        List<Tree> leaves = new ArrayList<>();
        leaves = tree.getLeaves(leaves);
        for (Tree leave : leaves) {
            String compare = leave.toString();
            if(compare.equals(data.connective) == true) {


             // How to get path but --> root

            }
        }

2 个答案:

答案 0 :(得分:0)

Tree有一个parent()方法,它返回树节点的父节点,如果没有,则返回null。所以你应该能够在你的for循环中做这样的事情:

for (Tree leave : leaves) {
    String compare = leave.toString();
    if(compare.equals(data.connective) == true) {
        Tree curr = leave;
        while (curr != null) {
            System.out.println(curr.toString());
            curr = curr.parent(); // will be null if no parent
        }
        break;
   }
}

答案 1 :(得分:0)

我认为这是另一种解决方案。

我首先使用DFS到达我想要的每个节点,然后使用一种称为的方法。

  • pathNodeToNode(node1,node2)

此方法来自StanfordNLP树类。这是方法链接https://nlp.stanford.edu/nlp/javadoc/javanlp-3.5.0/edu/stanford/nlp/trees/Tree.html

希望这可能对其他人有所帮助。