前面的答案虽然是正确的,但会遍历解析树中的所有节点。虽然没有现成的方法可以返回 POS 标签计数,但您可以使用edu.stanford.nlp.trees.Trees
类中的方法直接获取叶节点,如下所示:
(我在Function
代码中使用 Guava 来增加一点优雅,但是一个简单的 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); }
};