我正在使用新的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
我获得了null
而beginPostion
我得到了-1。
如何正确保留原始字符串中单词的开始位置进行解析?如果可能的话,我该如何获得NER? (beginPosition
在我的案例中实际上更重要)
答案 0 :(得分:2)
在您的情况下,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();
}