2011-04-18 231 views
19

我需要将单词分类为他们的词类。就像一个动词,名词,副词等。 我用在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'

回答

13

这个答案可能是关闭的基础,在这种情况下,我会删除它,因为我没有NLTK安装在这里试试,但我认为你可以做到:

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

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

编辑:我尝试这样做,当我回到家,它确实工作。

+0

看着节点属性之前,你要检查isinstance(sent3 [2],树) (在从nltk.tree导入树之后)。 – Jacob 2011-04-19 16:00:56

+0

@Jacob感谢队友,真的很有帮助。我面临的下一个问题是如何知道一个元素是否是一棵树。因为我需要使用for循环遍历元素。 **如果isinstance(sent3 [2],树)**是我一直在寻找这一切。再次感谢。当前版本(3.1)中的 – Asl506 2011-04-20 15:22:34

+6

'node'被替换为'label()' – Vladimir 2016-01-21 14:36:33

3

下面是我的代码:

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

我BDK同意

sent3[2].node

O/P - '东北'

我认为在NLTK做无功能它解决方案将工作,但供参考,你可以检查here

的循环问题,你可以这样做: -

for i in range(len(sent3)): 
    if "NE" in str(sent3[i]): 
      print sent3[i].node 

我在NLTK执行这一点,它工作正常..

0

现在sent3 [2] .node已经过时。

使用sent3 [2] .label(),而不是

0

这将工作

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