ptree: examples

>>> TREE = ("<s><np><jj>Snow</jj><nn>flakes</nn></np>"
...         "<vp tense='past'><v>fell</v>"
...         "<pp><p>on</p><np><dt>the</dt><nn>table</nn></np></pp>"
...         "</vp></s>")
...
>>> from ptree import ParentedTree as PT
>>> sent = PT.fromstring(TREE)
>>> table = sent[1][1][1][1]
>>> print PT.tostring(table)
<nn>table</nn>
>>> print PT.tostring(table.parent())
<np><dt>the</dt><nn>table</nn></np>
>>> def spine(elt):
...     if elt is None: return []
...     return [elt.tag] + spine(elt.parent())
>>> print spine(table)
['nn', 'np', 'pp', 'vp', 's']
>>> def spine_with_attribs(elt):
...     if elt is None: return []
...     label = elt.tag
...     if elt.attrib:
...         attrib = ['%s=%s' % i for i in elt.attrib.items()]
...         label += '<%s>' % ', '.join(attrib)
...     return [label] + spine_with_attribs(elt.parent())
>>> print spine_with_attribs(table)
['nn', 'np', 'pp', 'vp<tense=past>', 's']