java - 解析后从单词中获取开始位置和/或 NER

标签 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();
}

对于 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();
}

关于java - 解析后从单词中获取开始位置和/或 NER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33396009/

相关文章:

java - 如何在每个 ActionBar 选项卡中使用不同的布局 (Android)

python - Keras LSTM 中隐藏状态的含义

java - 在 Java 中构建/运行流式 Weka 文本分类器

java - 训练 NER 模型时存在斯坦福 corenlp 错误

python - python 中的 JsonRpc 客户端

java - 斯坦福 CoreNLP 非常慢

java - 为什么将对最终类实例的引用声明为最终的?

java - 加载纹理 LWJGL

java - 在 Java 中从字符串中获取单词并将其更改为小写。

nlp - gensim doc2vec "intersect_word2vec_format"命令