【问题标题】:Can we find sentences around an entity tagged via NER?我们可以在通过 NER 标记的实体周围找到句子吗?
【发布时间】:2019-11-24 17:59:38
【问题描述】:

我们已经准备好一个模型,它可以识别一个自定义命名实体。问题是如果给出了整个文档,那么如果只给出几个句子,模型就不能按预期工作,它会给出惊人的结果。

我想选择一个标记实体前后的两个句子。

例如。如果文档的一部分有世界科伦坡(标记为 GPE),我需要在标记之前选择两个句子,在标记之后选择 2 个句子。我尝试了几种方法,但复杂度太高了。

spacy 中是否有一种内置方法可以解决这个问题?

我正在使用 python 和 spacy。

我尝试通过识别标签的索引来解析文档。但这种方法真的很慢。

【问题讨论】:

    标签: machine-learning nlp spacy


    【解决方案1】:

    看看你是否可以改进自定义命名实体识别器可能是值得的,因为额外的上下文影响性能应该是不寻常的,如果你解决了这个问题,它可能会整体上更好地工作。

    但是,关于您关于周围句子的具体问题:

    TokenSpan(实体是Span)有一个.sent 属性,它为您提供作为Span 的覆盖句。如果您在给定句子的开始/结束标记之前/之后查看标记,您可以获得文档中任何标记的上一个/下一个句子。

    import spacy
    
    def get_previous_sentence(doc, token_index):
        if doc[token_index].sent.start - 1 < 0:
            return None
        return doc[doc[token_index].sent.start - 1].sent
    
    def get_next_sentence(doc, token_index):
        if doc[token_index].sent.end + 1 >= len(doc):
            return None
        return doc[doc[token_index].sent.end + 1].sent
    
    nlp = spacy.load('en_core_web_lg')
    
    text = "Jane is a name. Here is a sentence. Here is another sentence. Jane was the mayor of Colombo in 2010. Here is another filler sentence. And here is yet another padding sentence without entities. Someone else is the mayor of Colombo right now."
    
    doc = nlp(text)
    
    for ent in doc.ents:
        print(ent, ent.label_, ent.sent)
        print("Prev:", get_previous_sentence(doc, ent.start))
        print("Next:", get_next_sentence(doc, ent.start))
        print("----")
    

    输出:

    Jane PERSON Jane is a name.
    Prev: None
    Next: Here is a sentence.
    ----
    Jane PERSON Jane was the mayor of Colombo in 2010.
    Prev: Here is another sentence.
    Next: Here is another filler sentence.
    ----
    Colombo GPE Jane was the mayor of Colombo in 2010.
    Prev: Here is another sentence.
    Next: Here is another filler sentence.
    ----
    2010 DATE Jane was the mayor of Colombo in 2010.
    Prev: Here is another sentence.
    Next: Here is another filler sentence.
    ----
    Colombo GPE Someone else is the mayor of Colombo right now.
    Prev: And here is yet another padding sentence without entities.
    Next: None
    ----
    

    【讨论】:

    • 有没有办法获取句子中任何选定单词周围的句子。假设我们的目标是获取上面示例中包含世界“市长”的当前句子以及围绕它的前一个和下一个句子,无论它们的标签如何。我们怎样才能做到这一点?
    猜你喜欢
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2021-08-31
    相关资源
    最近更新 更多