使用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树更容易。
此链接的代码和详细信息;查看更多信息
您还可以继续使用以下功能提取单词:
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人的输出
0
我使用NLTK的
ne_chunk
从文本中提取命名实体:但是我不知道如何将这些实体保存到列表中?例如–
谢谢。