Search in sources :

Example 1 with TreeGraphNode

use of edu.stanford.nlp.trees.TreeGraphNode in project CoreNLP by stanfordnlp.

the class DependencyParser method predict.

/**
   * Determine the dependency parse of the given sentence using the loaded model.
   * You must first load a parser before calling this method.
   *
   * @throws java.lang.IllegalStateException If parser has not yet been loaded and initialized
   *         (see {@link #initialize(boolean)}
   */
public GrammaticalStructure predict(CoreMap sentence) {
    if (system == null)
        throw new IllegalStateException("Parser has not been  " + "loaded and initialized; first load a model.");
    DependencyTree result = predictInner(sentence);
    // The rest of this method is just busy-work to convert the
    // package-local representation into a CoreNLP-standard
    // GrammaticalStructure.
    List<CoreLabel> tokens = sentence.get(CoreAnnotations.TokensAnnotation.class);
    List<TypedDependency> dependencies = new ArrayList<>();
    IndexedWord root = new IndexedWord(new Word("ROOT"));
    root.set(CoreAnnotations.IndexAnnotation.class, 0);
    for (int i = 1; i <= result.n; i++) {
        int head = result.getHead(i);
        String label = result.getLabel(i);
        IndexedWord thisWord = new IndexedWord(tokens.get(i - 1));
        IndexedWord headWord = head == 0 ? root : new IndexedWord(tokens.get(head - 1));
        GrammaticalRelation relation = head == 0 ? GrammaticalRelation.ROOT : makeGrammaticalRelation(label);
        dependencies.add(new TypedDependency(relation, headWord, thisWord));
    }
    // Build GrammaticalStructure
    // TODO ideally submodule should just return GrammaticalStructure
    TreeGraphNode rootNode = new TreeGraphNode(root);
    return makeGrammaticalStructure(dependencies, rootNode);
}
Also used : IndexedWord(edu.stanford.nlp.ling.IndexedWord) HasWord(edu.stanford.nlp.ling.HasWord) TaggedWord(edu.stanford.nlp.ling.TaggedWord) Word(edu.stanford.nlp.ling.Word) TypedDependency(edu.stanford.nlp.trees.TypedDependency) CoreLabel(edu.stanford.nlp.ling.CoreLabel) CoreAnnotations(edu.stanford.nlp.ling.CoreAnnotations) GrammaticalRelation(edu.stanford.nlp.trees.GrammaticalRelation) TreeGraphNode(edu.stanford.nlp.trees.TreeGraphNode) IndexedWord(edu.stanford.nlp.ling.IndexedWord)

Aggregations

CoreAnnotations (edu.stanford.nlp.ling.CoreAnnotations)1 CoreLabel (edu.stanford.nlp.ling.CoreLabel)1 HasWord (edu.stanford.nlp.ling.HasWord)1 IndexedWord (edu.stanford.nlp.ling.IndexedWord)1 TaggedWord (edu.stanford.nlp.ling.TaggedWord)1 Word (edu.stanford.nlp.ling.Word)1 GrammaticalRelation (edu.stanford.nlp.trees.GrammaticalRelation)1 TreeGraphNode (edu.stanford.nlp.trees.TreeGraphNode)1 TypedDependency (edu.stanford.nlp.trees.TypedDependency)1