用于多种语言的名称实体识别(NER)

2024-10-04 05:24:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一些代码来执行命名实体识别(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)

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


Tags: 代码textfrom文本import语言nlpspacy
1条回答
网友
1楼 · 发布于 2024-10-04 05:24:06

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)

相关问题 更多 >