你如何使用nltk.util.breadth_first进行搜索?

时间:2018-03-07 21:12:41

标签: python nlp nltk

我试图使用breadth_first搜索(首先)特定叶子词,然后在ParentedTree中搜索某个标签(NP)。如果已经有了它的方法,我真的不想自己实现它。这就是我所尝试过的(包括我如何制作树,以防我搞砸了):

import nltk
from nltk.util import breadth_first

grammar = nltk.data.load("/path/to/grammar.cfg")
parser = nltk.parse.EarleyChartParser(grammar)
sent = "They are happy people"
parse1 = list(parser.parse(sent.split()))
tree1 = nltk.tree.ParentedTree.convert(parse1[0])
bf = breadth_first(tree1)

这给了我一个生成器对象,但我不知道如何使用它来搜索我想要的东西(代词"他们")。我尝试在bf中做一个简单的"节点:print(节点)"它将字符串的每个字母单独打印出来,永远重复,直到我不得不关闭窗口。

我已经阅读了文档,并且我已经完成了大量的Google搜索,但我找不到实际用于搜索的示例。我究竟做错了什么?

1 个答案:

答案 0 :(得分:3)

nltk.util.breadth_first方法执行您提供的树的广度优先遍历作为参数。要将其用作搜索机制,您需要检查生成器中返回的每个结果的值。

如果遍历由breadth_first返回的生成器的结果并在遍历的每一步输出结果,您可以看到它遇到树中的每个节点(以BFS顺序)并最终遇到叶节点和字符节点树也是。

因此,对于您的情况,您希望使用此生成器,并在每个节点检查一些值,以查看您是否已到达具有您在搜索中查找的符号或叶标记的节点。

这是一个示例句子,它来自nltk的解析树,以及遍历树的遍历。

祝你好运!

>>> sentence
'They capture mice in the cells'
>>> parse
Tree('S', [Tree('NP', [Tree('PRP', ['They'])]), Tree('VP', [Tree('VBP', ['capture']), Tree('NP', [Tree('Nom', [Tree('Nom', [Tree('NNS', ['mice'])]), Tree('PP', [Tree('Prep', ['in']), Tree('NP', [Tree('Det', ['the']), Tree('Nom', [Tree('NNS', ['cells'])])])])])])])])
>>> i = 0
>>> for node in breadth_first(parse):
...     print("*"*10)
...     print(node)
...     print(type(node))
...     if i > 10:
...             break
...     i += 1
...
**********
(S
  (NP (PRP They))
  (VP
    (VBP capture)
    (NP
      (Nom
        (Nom (NNS mice))
        (PP (Prep in) (NP (Det the) (Nom (NNS cells))))))))
<class 'nltk.tree.Tree'>
**********
(NP (PRP They))
<class 'nltk.tree.Tree'>
**********
(VP
  (VBP capture)
  (NP
    (Nom
      (Nom (NNS mice))
      (PP (Prep in) (NP (Det the) (Nom (NNS cells)))))))
<class 'nltk.tree.Tree'>
**********
(PRP They)
<class 'nltk.tree.Tree'>
**********
(VBP capture)
<class 'nltk.tree.Tree'>
**********
(NP
  (Nom
    (Nom (NNS mice))
    (PP (Prep in) (NP (Det the) (Nom (NNS cells))))))
<class 'nltk.tree.Tree'>
**********
They
<class 'str'>
**********
capture
<class 'str'>
**********
(Nom
  (Nom (NNS mice))
  (PP (Prep in) (NP (Det the) (Nom (NNS cells)))))
<class 'nltk.tree.Tree'>
**********
T
<class 'str'>
**********
h
<class 'str'>
**********
e
<class 'str'>
相关问题