Python中NLTK的命名实体识别。识别东北

2024-10-05 14:30:40 发布

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

我需要把单词分成词类。像动词、名词、副词等。。 我用了

nltk.word_tokenize() #to identify word in a sentence 
nltk.pos_tag()       #to identify the parts of speech
nltk.ne_chunk()      #to identify Named entities. 

这是一棵树。 例如

>>> sentence = "I am Jhon from America"
>>> sent1 = nltk.word_tokenize(sentence )
>>> sent2 = nltk.pos_tag(sent1)
>>> sent3 =  nltk.ne_chunk(sent2, binary=True)
>>> sent3
Tree('S', [('I', 'PRP'), ('am', 'VBP'), Tree('NE', [('Jhon', 'NNP')]), ('from', 'IN'), Tree('NE', [('America', 'NNP')])])

当访问此树中的元素时,我执行了以下操作:

>>> sent3[0]
('I', 'PRP')
>>> sent3[0][0]
'I'
>>> sent3[0][1]
'PRP'

但当访问命名实体时:

>>> sent3[2]
Tree('NE', [('Jhon', 'NNP')])
>>> sent3[2][0]
('Jhon', 'NNP')
>>> sent3[2][1]    
Traceback (most recent call last):
  File "<pyshell#121>", line 1, in <module>
    sent3[2][1]
  File "C:\Python26\lib\site-packages\nltk\tree.py", line 139, in __getitem__
    return list.__getitem__(self, index)
IndexError: list index out of range

我得到了上面的错误。

我想要的是得到类似于前一个“PRP”的“NE”输出,这样我就无法识别哪个单词是命名实体。 在python中使用NLTK有什么方法吗??如果是,请发布命令。或者树库中有一个函数来执行此操作吗?我需要节点值“NE”


Tags: toinpostree单词sentencewordne
3条回答

这个答案可能是偏离基准的,在这种情况下,我将删除它,因为我没有安装NLTK来尝试它,但我认为您可以这样做:

   >>> sent3[2].node
   'NE'

sent3[2][0]返回树的第一个子节点,而不是节点本身

编辑:我回家后试过这个,确实有效。

这样就行了

for sent in chunked_sentences:
  for chunk in sent:
    if hasattr(chunk, "label"):
        print(chunk.label())

以下是我的代码:

chunks = ne_chunk(postags, binary=True)
for c in chunks:
  if hasattr(c, 'node'):
    myNE.append(' '.join(i[0] for i in c.leaves()))

相关问题 更多 >