我需要把单词分成它们的词性。如动词、名词、副词等。我使用了
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‘
发布于 2011-04-19 04:58:10
这个答案可能是错误的,在这种情况下,我将删除它,因为我没有在这里安装NLTK来尝试它,但我认为你可以这样做:
>>> sent3[2].node
'NE'sent3[2][0]返回树的第一个子级,而不是节点本身
编辑:当我回到家的时候,我尝试了一下,它确实起作用了。
发布于 2013-02-15 13:11:50
下面是我的代码:
chunks = ne_chunk(postags, binary=True)
for c in chunks:
if hasattr(c, 'node'):
myNE.append(' '.join(i[0] for i in c.leaves()))发布于 2017-08-29 03:11:09
这将会起作用
for sent in chunked_sentences:
for chunk in sent:
if hasattr(chunk, "label"):
print(chunk.label())https://stackoverflow.com/questions/5708352
复制相似问题