解析后从单词中获取 begin poisitions and/or NER

Get begin poisitions and/or NER from words after parsing

我正在使用新的 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();
}

对于 tag 我正确地得到了 POS 标签,对于 ner 我得到了 null 而对于 beginPostion 我总是得到 -1。

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

在你的例子中,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();
}