我需要将单词分类为他们的词类。就像一个动词,名词,副词等。 我用在Python中为NLTK命名实体识别。识别NE
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
我得到上述错误。
我想要的是得到输出为'NE'类似于以前的'PRP',所以我无法确定哪个单词是一个命名实体。 是否有任何方式与Python中的NLTK做这个?如果是这样,请发布命令。或者在树库中有一个函数来做到这一点?我需要的节点值'NE'
看着节点属性之前,你要检查isinstance(sent3 [2],树) (在从nltk.tree导入树之后)。 – Jacob 2011-04-19 16:00:56
@Jacob感谢队友,真的很有帮助。我面临的下一个问题是如何知道一个元素是否是一棵树。因为我需要使用for循环遍历元素。 **如果isinstance(sent3 [2],树)**是我一直在寻找这一切。再次感谢。当前版本(3.1)中的 – Asl506 2011-04-20 15:22:34
'node'被替换为'label()' – Vladimir 2016-01-21 14:36:33