Tree parsing

General utilities for parsing a list of lines into a hierarchical structure.

tree_parsing.collect_hierarchy(lines, level_fun, read_fun=<function <lambda>>, assemble_fun=<function <lambda>>)

Reorders a list of lines that can be mapped to a level via level_fun into a hierarchical structure of the kind

(root_line,
     [(child_line,
          [(grandchild_line,
              [...])]),
      (sibling_line,
          [...]),
      ...])

The lines can be parsed/transformed with read_fun, and the nodes can be transformed with assemble_fun.

A line’s parent is the last previous line which satisfes the relation level_fun(parent_line) == level_fun(line) - 1.

Recursive function.

Parameters
  • lines (list of str) – The lines to be inserted in a tree;

  • level_fun (callable(string) -> int) – A function that computes the level for each line.

  • read_fun (callable(string) -> ParsedObject) – A function to parse the line. Default: identity function.

  • assemble_fun (callable(ParsedObject, list of AssembledObject) -> AssembledObjects) – A function that is used to assemble the result. Default: lambda root,children : (root,children).

Returns

assembled – The result

Return type

AssembledObject