【发布时间】:2018-05-15 14:17:03
【问题描述】:
我正在使用斯坦福 NLP 生成文档解析树。然后,我想遍历这些文档并存储所有 2 或 3 个单词长的短语,它们是 VP(动词短语)或 NP(名词短语)的一部分。我可以使用什么策略来实现这一目标?
【问题讨论】:
-
请查看更新后的答案。已经有一些内置方法可以在树中查找我的原始答案未使用的成分。我觉得这个新版本更好。
标签: nlp stanford-nlp
我正在使用斯坦福 NLP 生成文档解析树。然后,我想遍历这些文档并存储所有 2 或 3 个单词长的短语,它们是 VP(动词短语)或 NP(名词短语)的一部分。我可以使用什么策略来实现这一目标?
【问题讨论】:
标签: nlp stanford-nlp
这里有一些示例代码将遍历一棵树并打印出 NP 和 VP 中的单词:
package edu.stanford.nlp.examples;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.trees.*;
import java.util.*;
public class ConstituentExample {
public static void main(String[] args) {
// set up pipeline properties
Properties props = new Properties();
props.setProperty("annotators", "tokenize,ssplit,pos,lemma,ner,parse");
// use faster shift reduce parser
props.setProperty("parse.model", "edu/stanford/nlp/models/srparser/englishSR.ser.gz");
props.setProperty("parse.maxlen", "100");
// set up Stanford CoreNLP pipeline
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
// build annotation for a review
Annotation annotation =
new Annotation("The small red car turned very quickly around the corner.");
// annotate
pipeline.annotate(annotation);
// get tree
Tree tree =
annotation.get(CoreAnnotations.SentencesAnnotation.class).get(0).get(TreeCoreAnnotations.TreeAnnotation.class);
System.out.println(tree);
Set<Constituent> treeConstituents = tree.constituents(new LabeledScoredConstituentFactory());
for (Constituent constituent : treeConstituents) {
if (constituent.label() != null &&
(constituent.label().toString().equals("VP") || constituent.label().toString().equals("NP"))) {
System.err.println("found constituent: "+constituent.toString());
System.err.println(tree.getLeaves().subList(constituent.start(), constituent.end()+1));
}
}
}
}
【讨论】: