我使用NLTK的ne_chunk
从文本中提取命名实体:
my_sent = "WASHINGTON -- In the wake of a string of abuses by New York police officers in the 1990s, Loretta E. Lynch, the top federal prosecutor in Brooklyn, spoke forcefully about the pain of a broken trust that African-Americans felt and said the responsibility for repairing generations of miscommunication and mistrust fell to law enforcement."
nltk.ne_chunk(my_sent, binary=True)
但我无法弄清楚如何将这些实体保存到列表中?例如。 -
print Entity_list
('WASHINGTON', 'New York', 'Loretta', 'Brooklyn', 'African')
感谢。
答案 0 :(得分:30)
nltk.ne_chunk
返回一个嵌套的nltk.tree.Tree
对象,因此您必须遍历Tree
对象才能到达网元。
查看Named Entity Recognition with Regular Expression: NLTK
>>> from nltk import ne_chunk, pos_tag, word_tokenize
>>> from nltk.tree import Tree
>>>
>>> def get_continuous_chunks(text):
... chunked = ne_chunk(pos_tag(word_tokenize(text)))
... continuous_chunk = []
... current_chunk = []
... for i in chunked:
... if type(i) == Tree:
... current_chunk.append(" ".join([token for token, pos in i.leaves()]))
... elif current_chunk:
... named_entity = " ".join(current_chunk)
... if named_entity not in continuous_chunk:
... continuous_chunk.append(named_entity)
... current_chunk = []
... else:
... continue
... return continuous_chunk
...
>>> my_sent = "WASHINGTON -- In the wake of a string of abuses by New York police officers in the 1990s, Loretta E. Lynch, the top federal prosecutor in Brooklyn, spoke forcefully about the pain of a broken trust that African-Americans felt and said the responsibility for repairing generations of miscommunication and mistrust fell to law enforcement."
>>> get_continuous_chunks(my_sent)
['WASHINGTON', 'New York', 'Loretta E. Lynch', 'Brooklyn']
答案 1 :(得分:8)
您还可以使用以下代码提取文本中每个名称实体的label
:
import nltk
for sent in nltk.sent_tokenize(sentence):
for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):
if hasattr(chunk, 'label'):
print(chunk.label(), ' '.join(c[0] for c in chunk))
<强>输出:强>
GPE WASHINGTON
GPE New York
PERSON Loretta E. Lynch
GPE Brooklyn
您可以看到Washington
,New York
和Brooklyn
GPE
表示地理政治实体
和Loretta E. Lynch
是PERSON
答案 2 :(得分:4)
当您获得tree
作为返回值时,我想您想要选择标有reloadTableview
以下是收集列表中所有内容的简单示例:
NE
这给出了:
import nltk
my_sent = "WASHINGTON -- In the wake of a string of abuses by New York police officers in the 1990s, Loretta E. Lynch, the top federal prosecutor in Brooklyn, spoke forcefully about the pain of a broken trust that African-Americans felt and said the responsibility for repairing generations of miscommunication and mistrust fell to law enforcement."
parse_tree = nltk.ne_chunk(nltk.tag.pos_tag(my_sent.split()), binary=True) # POS tagging before chunking!
named_entities = []
for t in parse_tree.subtrees():
if t.label() == 'NE':
named_entities.append(t)
# named_entities.append(list(t)) # if you want to save a list of tagged words instead of a tree
print named_entities
或作为清单列表:
[Tree('NE', [('WASHINGTON', 'NNP')]), Tree('NE', [('New', 'NNP'), ('York', 'NNP')])]
答案 3 :(得分:3)
Tree
是一个列表。块是子树,非块词是常规字符串。因此,让我们从列表中删除,从每个块中提取单词,然后加入它们。
>>> chunked = nltk.ne_chunk(my_sent)
>>>
>>> [ " ".join(w for w, t in elt) for elt in chunked if isinstance(elt, nltk.Tree) ]
['WASHINGTON', 'New York', 'Loretta E. Lynch', 'Brooklyn']
答案 4 :(得分:3)
使用nltk.chunk中的tree2conlltags。 ne_chunk还需要标记单词标记的pos标记(因此需要word_tokenize)。
from nltk import word_tokenize, pos_tag, ne_chunk
from nltk.chunk import tree2conlltags
sentence = "Mark and John are working at Google."
print(tree2conlltags(ne_chunk(pos_tag(word_tokenize(sentence))
"""[('Mark', 'NNP', 'B-PERSON'),
('and', 'CC', 'O'), ('John', 'NNP', 'B-PERSON'),
('are', 'VBP', 'O'), ('working', 'VBG', 'O'),
('at', 'IN', 'O'), ('Google', 'NNP', 'B-ORGANIZATION'),
('.', '.', 'O')] """
这将为您提供元组列表:[(token,pos_tag,name_entity_tag)] 如果这个列表不是你想要的,那么从列表中解析你想要的列表肯定更容易,然后是一个nltk树。
this link的代码和详细信息;查看更多信息
您还可以继续只提取单词,使用以下功能:
def wordextractor(tuple1):
#bring the tuple back to lists to work with it
words, tags, pos = zip(*tuple1)
words = list(words)
pos = list(pos)
c = list()
i=0
while i<= len(tuple1)-1:
#get words with have pos B-PERSON or I-PERSON
if pos[i] == 'B-PERSON':
c = c+[words[i]]
elif pos[i] == 'I-PERSON':
c = c+[words[i]]
i=i+1
return c
print(wordextractor(tree2conlltags(nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sentence))))
修改添加了输出文档字符串 **编辑*仅为B-Person添加输出
答案 5 :(得分:1)
您也可以考虑使用Spacy:
import spacy
nlp = spacy.load('en')
doc = nlp('WASHINGTON -- In the wake of a string of abuses by New York police officers in the 1990s, Loretta E. Lynch, the top federal prosecutor in Brooklyn, spoke forcefully about the pain of a broken trust that African-Americans felt and said the responsibility for repairing generations of miscommunication and mistrust fell to law enforcement.')
print([ent for ent in doc.ents])
>>> [WASHINGTON, New York, the 1990s, Loretta E. Lynch, Brooklyn, African-Americans]
答案 6 :(得分:1)
nltk.ne_chunk返回一个嵌套的nltk.tree.Tree对象,因此您必须遍历Tree对象才能到达NE。您可以使用列表推导来做同样的事情。
import nltk
my_sent = "WASHINGTON -- In the wake of a string of abuses by New York police officers in the 1990s, Loretta E. Lynch, the top federal prosecutor in Brooklyn, spoke forcefully about the pain of a broken trust that African-Americans felt and said the responsibility for repairing generations of miscommunication and mistrust fell to law enforcement."
word = nltk.word_tokenize(my_sent)
pos_tag = nltk.pos_tag(word)
chunk = nltk.ne_chunk(pos_tag)
NE = [ " ".join(w for w, t in ele) for ele in chunk if isinstance(ele, nltk.Tree)]
print (NE)