2016-03-23 32 views
0

這是斯坦福解析器Stanford Parser:如何獲得C的父級路徑---> root?

This is a picture of Stanford Parser

圖片我有斯坦福解析器樹爲圖片。我想獲得C'parent的路徑 - >以root身份。例如:「but」'parent - > root = CC S Root的路徑,或者「it」parent - > root的路徑:PRP NP VP VP S S Root。但我不知道該怎麼做。我使用斯坦福分析器來解析語句。

 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 

      } 
     } 

回答

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; 
    } 
} 
+0

我試過先使用Tree.parent()或Tree.parent(curr)。但輸出顯示錯誤或錯誤的答案.... – drag

+0

這將是非常有用的信息,包括在您原來的問題。你究竟做了什麼,輸出是什麼? – whrrgarbl

+0

謝謝!這真的很有用。我修復並找到解決方法。謝謝:D – drag