如何导航nltk.tree.tree?
我用以下句子拼凑了一个句子:如何导航nltk.tree.tree?,tree,nltk,Tree,Nltk,我用以下句子拼凑了一个句子: grammar = ''' NP:
grammar = '''
NP:
{<DT>*(<NN.*>|<JJ.*>)*<NN.*>}
NVN:
{<NP><VB.*><NP>}
'''
chunker = nltk.chunk.RegexpParser(grammar)
tree = chunker.parse(tagged)
print tree
但现在我被困在试图找出如何导航。我希望能够找到NVN子树,并访问左侧的名词短语(“the_Pigs”)、动词(“are”)和右侧的名词短语(“布里斯托尔朋克摇滚乐队”)。我该怎么做?试试这个:
for a in tree:
if type(a) is nltk.Tree:
if a.node == 'NVN': # This climbs into your NVN tree
for b in a:
if type(b) is nltk.Tree and b.node == 'NP':
print b.leaves() # This outputs your "NP"
else:
print b # This outputs your "VB.*"
它的输出是:
[(‘猪’,‘NNS’)]
(“are”、“VBP”)
[('a','DT'),('Bristol-based','JJ'),('punk','NN'),('rock','NN'),
('band','NN')]
当然,你可以编写自己的深度优先搜索。。。但是有一个更简单(更好)的方法。如果希望每个子树都以NVM为根,请使用树的子树方法并定义过滤器参数
>>> print t
(S
(NVN
(NP The_Pigs/NNS)
are/VBP
(NP a/DT Bristol-based/JJ punk/NN rock/NN band/NN))
that/WDT
formed/VBN
in/IN
1977/CD
./.)
>>> for i in t.subtrees(filter=lambda x: x.node == 'NVN'):
... print i
...
(NVN
(NP The_Pigs/NNS)
are/VBP
(NP a/DT Bristol-based/JJ punk/NN rock/NN band/NN))
尝试:
下面是一个代码示例,用于生成带有标签“NP”的所有子树
def filt(x):
return x.label()=='NP'
for subtree in t.subtrees(filter = filt): # Generate all subtrees
print subtree
对于兄弟姐妹,您可能需要查看方法ParentedTree.left\u sibbins()
有关更多详细信息,这里有一些有用的链接
#一些基本用法和示例
#使用这些方法制作的笔记本
#所有带源代码的api你能发布叶节点的完整语法吗,然后我可以给你一个清晰的示例?另一个DFS示例(带
ParentedTree
):是的,谢谢。请注意,NLTK的接口可能会随着时间的推移而更改。对于Python 3.5和NLTK 3.2.2,lambda函数应该使用node:filter=lambda x:x.label()=“NP”的label()属性
ROOT = 'ROOT'
tree = ...
def getNodes(parent):
for node in parent:
if type(node) is nltk.Tree:
if node.label() == ROOT:
print "======== Sentence ========="
print "Sentence:", " ".join(node.leaves())
else:
print "Label:", node.label()
print "Leaves:", node.leaves()
getNodes(node)
else:
print "Word:", node
getNodes(tree)
def filt(x):
return x.label()=='NP'
for subtree in t.subtrees(filter = filt): # Generate all subtrees
print subtree