Parsing files -- pyparsing to the rescue?

Giovanni Bajo raNOsky at deveSPAMler.com
Mon Jan 16 16:05:41 EST 2006


rh0dium wrote:

> I have a file which I need to parse and I need to be able to break it
> down by sections.  I know it's possible but I can't seem to figure this
> out.
>
>     The sections are broken by <> with one or more keywords in the <>.
> What I want to do is to be able to pars a particular section of the
> file.  So for example I need to be able to look at the SYSLIB section.
> Presumably the sections are
>
>
> <SYSLIB>
> Sys Data
> Sys-Data
> asdkData
> Data
> <LOGLVS>
> Data
> Data
> Data
> Data
> <SOME SECTION>
> Data
> Data
> Data
> Data
> <NETLIST>
> Data
> Data
> Data
> Data
> <NET>

Given your description, pyparsing doesn't feel like the correct tool:

secs = {}
for L in file("foo.txt", "rU"):
     L = L.rstrip("\n")
     if re.match(r"<.*>", L):
        name = L[1:-1]
        secs[name] = []
     else:
        secs[name].append(L)

-- 
Giovanni Bajo





More information about the Python-list mailing list