【问题标题】:Name Entity Recognition (NER) for multiple languages多种语言的名称实体识别 (NER)
【发布时间】:2021-06-27 12:23:35
【问题描述】:

我正在编写一些代码来执行命名实体识别 (NER),这对于英文文本来说非常好。但是,我希望能够将 NER 应用于 任何 语言。为此,我想 1)识别文本的语言,然后 2)将 NER 应用于识别的语言。对于第 2 步,我怀疑 A) 将文本翻译成英文,然后应用 NER(英文),或 B) 应用所识别语言的 NER。

下面是我到目前为止的代码。我希望 NER 在第一次识别该语言后,可以为 text2 或任何其他语言工作:

import spacy
from spacy_langdetect import LanguageDetector
from langdetect import DetectorFactory

text = 'In 1793, Alexander Hamilton recruited Webster to move to New York City and become an editor for a Federalist Party newspaper.'
text2 = 'Em 1793, Alexander Hamilton recrutou Webster para se mudar para a cidade de Nova York e se tornar editor de um jornal do Partido Federalista.'

# Step 1: Identify the language of a text
DetectorFactory.seed = 0
nlp = spacy.load('en_core_web_sm')
nlp.add_pipe(LanguageDetector(), name='language_detector', last=True)
doc = nlp(text)
print(doc._.language)

# Step 2: NER
Entities = [(str(x), x.label_) for x in nlp(str(text)).ents]
print(Entities)

有人有这方面的经验吗?非常感谢!

【问题讨论】:

    标签: python nlp spacy named-entity-recognition


    【解决方案1】:

    Spacy 需要为正确的语言加载正确的模型。

    有关可用型号,请参阅https://spacy.io/usage/models

    import spacy
    from langdetect import detect
    nlp={}    
    for lang in ["en", "es", "pt", "ru"]: # Fill in the languages you want, hopefully they are supported by spacy.
        if lang == "en":
            nlp[lang]=spacy.load(lang + '_core_web_lg')
        else: 
            nlp[lang]=spacy.load(lang + '_core_news_lg')
    
    def entites(text):
         lang = detect(text)
         try:
             nlp2 =nlp[lang]
         except KeyError:
             return Exception(lang + " model is not loaded")
         return [(str(x), x.label_) for x in nlp2(str(text)).ents]
    

    然后,您可以同时运行这两个步骤

    ents = entites(text)
    print(ents)
    

    【讨论】:

    • 非常感谢乌里!我必须对您的代码进行一些调整,否则效果很好。我将对您的代码进行一些小的修改并接受它。
    猜你喜欢
    • 1970-01-01
    • 2017-06-19
    • 2012-04-20
    • 2010-09-07
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多