texttree is a basic python module for parsing textual representations of trees of strings which use indentation to indicate nesting - like the following:

Root non-leaf leaf1 leaf2 leaf3

There are two interesting functions in texttree: build_tree and build_forest.

Given a string containing a textual representation of a tree build_tree this returns a texttree.Tree object, containing string values.

build_forest is like build_tree but will a single string consisting of several concatenated tree representations and return a list of trees.

Indentation, trailing or leading whitespace, and trailing whitspace on lines is stripped.

Installing

Example use case

The following code parses a text tree and turns it into an HTML nested list representing this tree.

import sys from texttree import build_tree def build_list(tree): child_string = "\n".join(build_list(subtree) for subtree in tree.children) return "<ul><li>%s%s</li></ul>" % (tree.value, child_string) tree = build_tree(sys.stdin.read()) print build_list(tree)