【问题标题】:Tokenizing Named Entities in Spacy在 Spacy 中标记命名实体
【发布时间】:2019-02-11 23:35:19
【问题描述】:

有人可以帮忙吗。

我正在尝试使用 Spacy 对文档进行标记,从而对命名实体进行标记。例如:

'纽约是美国的一个城市'

将被标记为:

['New York', 'is', 'a', 'city', 'in', 'the', 'United States of America']

非常欢迎任何有关如何执行此操作的提示。看过使用 span.merge(),但没有成功,但我是编码新手,所以可能错过了一些东西。

提前谢谢你

【问题讨论】:

  • 到目前为止你有什么代码?您是否使用 Spacy 的 NER 标记功能来识别实体令牌的开始和结束?
  • 我已经取得了一些进展,代码如下: import spacy from spacy.pipeline import merge_entities print('setting up pipeline') coref_nlp = spacy.load('en_coref_md') spacy_nlp = spacy. load('en_core_web_sm') spacy_nlp.add_pipe(merge_entities) spacy_nlp.add_pipe(spacy_nlp.create_pipe('sentencizer')) doc = '纽约是美国的一个城市。这是一个令人兴奋的地方' print('applying pipelines') new_doc = spacy_nlp(coref_nlp(doc)._.coref_resolved) # 用根引用替换共同引用实体
  • 这是它的标记化方式: doc_array = [] print('Tokenizing document') for sentence in new_doc.sents: doc_array.append([(token.text).lower() for token in句子 if (not token.is_stop and token.pos_ != "PUNCT" and token.text != '\n')]) print(doc_array)
  • 您对如何改进有任何想法吗?我要分析的主要文件是乔治·布什 9/11 后的演讲:millercenter.org/the-presidency/presidential-speeches/…
  • 请编辑您的问题以包含您粘贴在 cmets 中的代码,使用正确的降价将其格式化为代码。粘贴在 cmets 中的代码很难审查。如果您正确格式化代码并添加到您的问题中,获得好的答案的可能性会更高。

标签: nlp tokenize spacy named-entity-recognition


【解决方案1】:

使用doc.retokenize 上下文管理器将实体跨度合并为单个标记。将其包装在 custom pipeline component 中,并将组件添加到您的语言模型中。

import spacy

class EntityRetokenizeComponent:
  def __init__(self, nlp):
    pass
  def __call__(self, doc):
    with doc.retokenize() as retokenizer:
        for ent in doc.ents:
            retokenizer.merge(doc[ent.start:ent.end], attrs={"LEMMA": str(doc[ent.start:ent.end])})
    return doc

nlp = spacy.load('en')
retokenizer = EntityRetokenizeComponent(nlp) 
nlp.add_pipe(retokenizer, name='merge_phrases', last=True)

doc = nlp("German Chancellor Angela Merkel and US President Barack Obama "
          "converse in the Oval Office inside the White House in Washington, D.C.")

[tok for tok in doc]

#[German,
# Chancellor,
# Angela Merkel,
# and,
# US,
# President,
# Barack Obama,
# converse,
# in,
# the Oval Office,
# inside,
# the White House,
# in,
# Washington,
# ,,
# D.C.]

【讨论】:

    【解决方案2】:

    更新:Spacy v3 已包含所需的功能。

    我还收回了我对“总统选举”(如下答案所介绍)的期望仍然是一个实体(但这可能取决于你的用例)

    from pprint import pprint
    
    import spacy
    from spacy.language import Language
    
    
    # Disabling components not needed (optional, but useful if run on a large dataset)
    nlp = spacy.load("en_core_web_sm", disable=["tok2vec", "parser", "senter", "lemmatizer", "tagger", "attribute_ruler"])
    nlp.add_pipe("merge_noun_chunks")
    nlp.add_pipe("merge_entities")
    print('Pipeline components included: ', nlp.pipe_names)
    
    example_text = "German Chancellor Angela Merkel and US President Barack Obama (Donald Trump as president-elect') converse in the Oval Office inside the White House in Washington, D.C."
    
    print('Tokens: ')
    pprint([
        token.text
        for token in nlp(example_text)
        # Including some of the conditions I find useful
        if not (
            token.is_punct
            or
            token.is_space
        )
    ])
    
    

    继续阅读原始答案:


    我想我已经重新解释了适用于 spaCy v3 的公认答案。它似乎至少会产生相同的输出。

    在侧面笔记中,我注意到它分手了一个短语,如“总统选民”到3.我正在修理原始答案的榜样,包括在希望有人与主要发表评论(或新答案的希望中)


    import spacy
    from spacy.language import Language
    
    
    class EntityRetokenizeComponent:
        def __init__(self, nlp):
            pass
    
        def __call__(self, doc):
            with doc.retokenize() as retokenizer:
                for ent in doc.ents:
                    retokenizer.merge(doc[ent.start:ent.end], attrs={"LEMMA": str(doc[ent.start:ent.end])})
            return doc
    
    @Language.factory("entity_retokenizer_component")
    def create_entity_retokenizer_component(nlp, name):
        return EntityRetokenizeComponent(nlp)
    
    nlp = spacy.load("en_core_web_sm")  # You might want to load something else here, see docs
    nlp.add_pipe("entity_retokenizer_component", name='merge_phrases', last=True)
    
    text = "German Chancellor Angela Merkel and US President Barack Obama (Donald Trump as president-elect') converse in the Oval Office inside the White House in Washington, D.C."
    tokened_text = [token.text for token in nlp(text)]
    
    print(tokened_text)
    
    # ['German',
    #  'Chancellor',
    #  'Angela Merkel',
    #  'and',
    #  'US',
    #  'President',
    #  'Barack Obama',
    #  '(',
    #  'Donald Trump',
    #  'as',
    #  'president',
    #  '-',
    #  'elect',
    #  ')',
    #  'converse',
    #  'in',
    #  'the Oval Office',
    #  'inside',
    #  'the White House',
    #  'in',
    #  'Washington',
    #  ',',
    #  'D.C.']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多