Help needed with nested parsing of file into objects

richard pullenjenna10 at gmail.com
Mon Jun 4 10:20:28 EDT 2012


On Jun 4, 3:14 pm, Alain Ketterlin <al... at dpt-info.u-strasbg.fr>
wrote:
> richard <pullenjenn... 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)

thank you both for your replies. Unfortunately it is a pre-existing
file format imposed by an external system that I can't
change. Thank you for the code snippet.



More information about the Python-list mailing list