python-3.x - 使用 NLTK 和 Spacy 的 NLP 命名实体识别

标签 python-3.x nlp nltk spacy named-entity-recognition

我在 NLTK 和 Spacy 上对以下句子使用了 NER,结果如下:

"Zoni I want to find a pencil, a eraser and a sharpener"

我在 Google Colab 上运行了以下代码。

import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag

ex = "Zoni I want to find a pencil, a eraser and a sharpener"

def preprocess(sent):
    sent = nltk.word_tokenize(sent)
    sent = nltk.pos_tag(sent)
    return sent

sent = preprocess(ex)
sent

#Output:
[('Zoni', 'NNP'),
 ('I', 'PRP'),
 ('want', 'VBP'),
 ('to', 'TO'),
 ('find', 'VB'),
 ('a', 'DT'),
 ('pencil', 'NN'),
 (',', ','),
 ('a', 'DT'),
 ('eraser', 'NN'),
 ('and', 'CC'),
 ('a', 'DT'),
 ('sharpener', 'NN')]

但是当我在同一个文本上使用 spacy 时,它没有返回任何结果

import spacy
from spacy import displacy
from collections import Counter
import en_core_web_sm
nlp = en_core_web_sm.load()

text = "Zoni I want to find a pencil, a eraser and a sharpener"

doc = nlp(text)
doc.ents

#Output:
()

它只对某些句子有效。

import spacy
from spacy import displacy
from collections import Counter
import en_core_web_sm
nlp = en_core_web_sm.load()

# text = "Zoni I want to find a pencil, a eraser and a sharpener"

text = 'European authorities fined Google a record $5.1 billion on Wednesday for abusing its power in the mobile phone market and ordered the company to alter its practices'

doc = nlp(text)
doc.ents

#Output:
(European, Google, $5.1 billion, Wednesday)

如果有什么问题请告诉我。

最佳答案

Spacy 模型是统计的。因此,这些模型识别的命名实体取决于训练这些模型的数据集。

根据 spacy 文档,命名实体是一个“真实世界的对象”,它被分配了一个名称——例如,一个人、一个国家、一个产品或一个书名。

例如,名称 Zoni 并不常见,因此模型不会将该名称识别为命名实体(人)。如果我在你的句子中将名字 Zoni 更改为 William spacyWilliam 识别为一个人。

import spacy
nlp = spacy.load('en_core_web_lg')

doc = nlp('William I want to find a pencil, a eraser and a sharpener')

for entity in doc.ents:
  print(entity.label_, ' | ', entity.text)
  #output
  PERSON  |  William

人们会假设铅笔橡皮卷笔刀是物体,因此它们可能被归类为产品,因为spacy documentation声明“对象”是产品。但是您句子中的 3 个对象似乎并非如此。

我还注意到,如果在输入文本中未找到命名实体,则输出将为空。

import spacy
nlp = spacy.load("en_core_web_lg")

doc = nlp('Zoni I want to find a pencil, a eraser and a sharpener')
if not doc.ents:
  print ('No named entities were recognized in the input text.')
else:
  for entity in doc.ents:
    print(entity.label_, ' | ', entity.text)

关于python-3.x - 使用 NLTK 和 Spacy 的 NLP 命名实体识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58210582/

相关文章:

python - 将列表中的值附加到字典中

python - 如何使用 lambda 将样式应用于 Pandas DataFrame

python - 如何总结对话中每个人的字数?

nlp - 如何找出英语的熵

python-2.7 - Python nltk.clean_html未实现

python - str.translate 给出 TypeError - Translate 接受一个参数(给定 2 个),在 Python 2 中工作

python-3.x - 使用exchangelib访问Outlook Exchange服务器阅读邮件时出现403错误

python - 无法将 numpy 数组转换为 JSON

java - 使用斯坦福 CoreNLP

python-3.x - 使用GenSim的短语之间的语义相似性