我正在使用新的 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)并且 ner
和 beginPosition
都设置正确。由于在你的例句中不存在可识别的实体 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();
}
关于java - 解析后从单词中获取开始位置和/或 NER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33396009/