2014-01-27 138 views
0

我一直在使用Stanford Parser進行CFG分析。我可以將輸出顯示爲樹狀結構,但我真正想要的是標記的數量。斯坦福分析器 - 標記計數

這樣我就可以出去,例如(從another query採取堆棧溢出):

(ROOT (S (NP (PRP$ My) (NN dog)) (ADVP (RB also)) (VP (VBZ likes) (NP (JJ eating) (NN sausage))) (. .))) 

但我真正想要的是一個CSV文件輸出標籤的計數:

PRP - 1 
JJ - 1 

斯坦福解析器可以這樣做,特別是當我想處理幾個文本文件,或者我應該使用不同的程序嗎?

回答

1

是的,這很容易實現。

你將需要:

 
import java.util.HashMap; 
import edu.stanford.nlp.trees.Tree; 

我從你現有的樹對象已經是其他問題的假設。 我懷疑你只想要一個帶有離開節點的列表(在你的例子中是PRP,NN,RB ...),但是你可以爲每個節點做一般的事情。

然後遍歷所有節點,只計算葉子:

Tree tree = ... 
for (int i = 1; i < tree.size(); i++) { 
    Tree node = tree.getNodeNumber(i); 

    if (node.isLeaf()) { 
    // count here 
    } 
} 

計數是使用一個HashMap完成後,你會發現這裏的計算器上的很多例子。 基本上從一個Hashmap開始,使用標記作爲鍵和標記計數作爲值。

編輯:對不起,糾正了代碼中的否定錯誤。

1

上一個答案在正確的情況下迭代瞭解析樹中的所有節點。

我使用番石榴的Function在代碼中一點點額外的優雅,但:雖然是返回POS標籤數沒有現成的方法,你可以使用在edu.stanford.nlp.trees.Trees類方法葉節點如下直接得到一個簡單的for循環將工作一樣好。

Tree tree = sentence.get(TreeAnnotation.class); // parse tree of the sentence 
List<CoreLabel> labels = Trees.taggedLeafLabels(tree); // returns the labels of the leaves in a Tree, augmented with POS tags. 
List<String> tags = Lists.transform(labels, getPOSTag); 
for (String tag : tags) 
    Collections.frequency(tags, tag); 

其中

Function<CoreLabel, String> getPOSTag = new Function<CoreLabel, String>() { 
    public String apply(CoreLabel core_label) { return core_label.get(PartOfSpeechAnnotation.class); } 
}; 
+0

優雅的回答,真的! –

+0

感謝您的幫助。對不起,如果這是顯而易見的,但這意味着創建一個Java模塊呢?目前我剛剛在終端命令行中運行它(例如,java -mx200m edu.stanford.nlp.parser.lexparser.LexicalizedParser -retainTMPSubcategories -outputFormat「wordsAndTags,penn,typedDependencies」englishPCFG.ser.gz mumbai.txt) – JRUK

+0

是的,你需要你自己的代碼。儘管斯坦福大學NLP的作者爲CLI的使用提供了很大的靈活性,但除了解析結果的直接輸出之外,您通常需要使用他們的API(順便提一下,這是非常有用的) 。 –