如何遍历NLTK树对象? [英] How to Traverse an NLTK Tree object?

查看:106
本文介绍了如何遍历NLTK树对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于括号内的解析,我可以将其转换为NLTK中的Tree对象,如下所示:

Given a bracketed parse, I could convert it into a Tree object in NLTK as such:

>>> from nltk.tree import Tree
>>> s = '(ROOT (S (NP (NNP Europe)) (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends)))) (. .)))'
>>> Tree.fromstring(s)
Tree('ROOT', [Tree('S', [Tree('NP', [Tree('NNP', ['Europe'])]), Tree('VP', [Tree('VBZ', ['is']), Tree('PP', [Tree('IN', ['in']), Tree('NP', [Tree('DT', ['the']), Tree('JJ', ['same']), Tree('NNS', ['trends'])])])]), Tree('.', ['.'])])])

但是当我尝试遍历它时,我只能访问最上面的树:

But when I try to traverse it, I can only access the top most Tree:

>>> for i in Tree.fromstring(s):
...     print i
... 
(S
  (NP (NNP Europe))
  (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends))))
  (. .))
>>> for i in Tree.fromstring(s):
...     print i, i.label()
... 
(S
  (NP (NNP Europe))
  (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends))))
  (. .)) S
>>> 

我可以进行如下深入的研究:

I could go one level deep as follows:

>>> for i in Tree.fromstring(s):
...     print i.subtrees()
... 
<generator object subtrees at 0x7f1eb1571410>
>>> for i in Tree.fromstring(s):
...     for j in i.subtrees():
...             print j
... 
(S
  (NP (NNP Europe))
  (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends))))
  (. .))
(NP (NNP Europe))
(NNP Europe)
(VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends))))
(VBZ is)
(PP (IN in) (NP (DT the) (JJ same) (NNS trends)))
(IN in)
(NP (DT the) (JJ same) (NNS trends))
(DT the)
(JJ same)
(NNS trends)
(. .)

但是有办法明智地遍历所有子树吗?

But is there a way to traverse all subtrees depth wise?

一个人应该如何在NLTK中遍历一棵树?

如何遍历NLTK中的所有子树?

推荐答案

也许我正在忽略事物,但这是你的追求吗?

Maybe I'm overlooking things, but is this what you're after?

import nltk
s = '(ROOT (S (NP (NNP Europe)) (VP (VBZ is) (PP (IN in) (NP (DT the) (JJ same) (NNS trends)))) (. .)))'
tree = nltk.tree.Tree.fromstring(s)
def traverse_tree(tree):
    # print("tree:", tree)
    for subtree in tree:
        if type(subtree) == nltk.tree.Tree:
            traverse_tree(subtree)
traverse_tree(tree)

它首先遍历您的树.

这篇关于如何遍历NLTK树对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆