解析后从单词开始poisitions和/或NER

时间:2015-10-28 16:06:22

标签: java nlp stanford-nlp

我正在使用新的Stanford CoreNLP NN解析器。这是代码的简化版本:

// Sentence to be parsed
String sentence = "This is an example sentence.";

// This is where we store the result from the parser. Initially set to "null".
GrammaticalStructure gs = null;

// Parse the sentence
DocumentPreprocessor tokenizer = new DocumentPreprocessor(new StringReader(sentence));
List<TaggedWord> tagged = null;
for (List<HasWord> sent : tokenizer) {
    tagged = tagger.tagSentence(sent);
    gs = parser.predict(tagged);
}

// Convert the GrammaticalStructure object (the parsing result) into a semantic graph
SemanticGraph semanticGraph = SemanticGraphFactory.generateUncollapsedDependencies(gs);

现在,当我遍历semanticGraph的顶点时,我可以得到POS标签,但我无法获得该单词的NER和开始位置。所以,当我这样做时:

for (IndexedWord vertex : new ArrayList<>(semanticGraph.vertexSet())){
    String tag = vertex.tag();
    String ner = vertex.ner();
    int beginPosition = vertex.beginPosition();
}

for tag我正确获得了POS代码,ner我获得了nullbeginPostion我得到了-1。

如何正确保留原始字符串中单词的开始位置进行解析?如果可能的话,我该如何获得NER? (beginPosition在我的案例中实际上更重要)

1 个答案:

答案 0 :(得分:2)

在您的情况下,NER标记不存在,因为您实际上并未在代码中执行此类注释。我不确定beginPosition

中未设置SemanticGraph的原因

强烈建议对于相互依赖的多个注释使用StanfordCoreNLP管道。通过Properties对象很容易(重新)配置它以使用不同的注释器。由于它可以使用多个线程,因此还有可能获得更好的性能。

这是一个简单的示例,其中包含一个管道,用于保存代码中的for循环。我已经测试过(CoreNLP 3.5.2)并且nerbeginPosition都设置正确。由于您的例句中不存在可识别的实体,ner始终为"O"。此外,如果您的文档中有多个句子,则必须遍历sentences列表。

Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

String sentence = "This is an example sentence.";
Annotation document = new Annotation(sentence);
pipeline.annotate(document);

List<CoreMap> sentences = document.get(SentencesAnnotation.class);
CoreMap map = sentences.get(0);
SemanticGraph semanticGraph = map.get(CollapsedCCProcessedDependenciesAnnotation.class);

for (IndexedWord vertex : new ArrayList<>(semanticGraph.vertexSet())) {
    String tag = vertex.tag();
    String ner = vertex.ner();
    int beginPosition = vertex.beginPosition();
}