Tree Traversal

It is standard to use a recursive function to traverse a tree. The listing in Example 7-7 demonstrates this.

Example 7-7. A recursive function to traverse a tree.

def traverse(t): try:

t.node except AttributeError: print t, else:

# Now we know that t.node is defined print '(', t.node, for child in t:

>>> t = nltk.Tree('(S (NP Alice) (VP chased (NP the rabbit)))') >>> traverse(t)

We have used a technique called duck typing to detect that t is a tree (i.e., t.node is defined).

Was this article helpful?

0 0

Post a comment