从图像解析器可以看到,返回NP,VP,PP,NP。我希望能够访问不同深度的所有短语。例如,在depth = 1中,有两个短语NP和VP,在depth = 2中,还有一些其他短语,在depth = 3中,还有其他一些短语。如何使用python访问属于depth = n的短语?
答案 0 :(得分:0)
package edu.stanford.nlp.examples;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.trees.*;
import java.util.*;
import java.util.stream.*;
public class ConstituencyParserExample {
public static void main(String[] args) {
String text = "The little lamb climbed the big mountain.";
// set up pipeline properties
Properties props = new Properties();
// set the list of annotators to run
props.setProperty("annotators", "tokenize,ssplit,pos,lemma,parse");
// build pipeline
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
// create a document object
CoreDocument document = new CoreDocument(text);
// annnotate the document
pipeline.annotate(document);
int maxDepth = 5;
for (CoreSentence sentence : document.sentences()) {
Set<Constituent> constituents = sentence.constituencyParse().constituents(
new LabeledScoredConstituentFactory(), maxDepth).stream().filter(
x -> x.label().value().equals("NP")).collect(Collectors.toSet());
for (Constituent constituent : constituents) {
System.out.println("---");
System.out.println("label: "+constituent.label().value());
System.out.println(sentence.tokens().subList(constituent.start(), constituent.end()+1));
}
}
}
}