Help needed with nested parsing of file into objects

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Mon Jun 4 10:14:39 EDT 2012


richard <pullenjenna10 at gmail.com> writes:

> Hi guys i am having a bit of dificulty finding the best approach /
> solution to parsing a file into a list of objects / nested objects any
> help would be greatly appreciated.
>
> #file format to parse .txt
> [code]
> An instance of TestArray
>  a=a
>  b=b
>  c=c
>  List of 2 A elements:
>   Instance of A element
[...]

Below is a piece of code that seems to work on your data. It builds a
raw tree, i leave it to you to adapt and built the objects you want. The
assumption is that the number of leading blanks faithfully denotes
depth.

As noted in another message, you're probably better off using an
existing syntax (json, python literals, yaml, xml, ...)

-- Alain.

#!/usr/bin/env python

import sys
import re

RE = re.compile("( *)(.*)")
stack = [("-",[])] # tree nodes are: (head,[children])
for line in sys.stdin:
    matches = RE.match(line)
    if len(matches.group(2)) > 0:
        depth = 1 + len(matches.group(1))
        while len(stack) > depth:
            stack[-2][1].append(stack[-1])
            del stack[-1]
            pass
        stack.append( (matches.group(2),[]) )
        pass
    pass
while len(stack) > 1:
    stack[-2][1].append(stack[-1])
    del stack[-1]
    pass

print(stack)



More information about the Python-list mailing list