20

我需要将单词分类为它们的词性。像动词、名词、副词等。我用

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”

4

6 回答 6

14

这个答案可能不正确,在这种情况下我会删除它,因为我没有在这里安装 NLTK 来尝试它,但我认为你可以这样做:

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

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

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

于 2011-04-18T20:58:10.060 回答
4

下面是我的代码:

chunks = ne_chunk(postags, binary=True)
for c in chunks:
  if hasattr(c, 'node'):
    myNE.append(' '.join(i[0] for i in c.leaves()))
于 2013-02-15T05:11:49.800 回答
2

这将起作用

for sent in chunked_sentences:
  for chunk in sent:
    if hasattr(chunk, "label"):
        print(chunk.label())
于 2017-08-28T19:11:09.160 回答
1

我同意 bdk

sent3[2].node

O/P - 'NE'

我认为 nltk 中没有功能可以做到这一点。上述解决方案将起作用,但作为参考,您可以在此处查看

对于循环问题,您可以执行以下操作:-

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

我已经在 nltk 中执行了这个,它工作正常..

于 2013-10-09T11:18:15.053 回答
1

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

使用 sent3[2].label() 代替

于 2017-04-11T17:34:02.577 回答
0

您可以将句子视为一棵树并循环遍历它。

entities = nltk.ne_chunk(text)
for c in entities:
    # Is an entity
    if isinstance(elem, nltk.Tree):
        print('elem: ', elem.leaves(), elem.label())
    else:
       # Not an entity
于 2021-12-03T04:31:08.093 回答