Convert a string to a list
Paul McGuire
ptmcg at austin.rr.com
Thu Apr 26 09:50:53 EDT 2007
On Apr 25, 9:02 pm, Paul McGuire <p... at austin.rr.com> wrote:
> On Apr 24, 12:30 pm, Nick Craig-Wood <n... at craig-wood.com> wrote:
>
>
>
> > Someone normally chimes in with pyparsing at this point...
>
> Well it *is* a short pyparsing routine, after all...
>
> -- Someone
>
> tests = """\
> ("." ".." "cdslib_cleanup.py" "cadence.py"
> "cdsinit_cdsenv_cleanup.py")
> ("." ("cadence.py" "foo_cleanup.py") "cdslib_cleanup.py" "cadence.py"
> "cdsinit_cdsenv_cleanup.py") """.splitlines()
>
> import pyparsing as pp
>
> LPAR,RPAR = map(pp.Suppress,"()")
> list_ = pp.Forward()
> list_ << ( LPAR +
> pp.ZeroOrMore( pp.quotedString | pp.Group(list_) ) +
> RPAR )
>
> for t in tests:
> result = list_.parseString(t)
> print result.asList()
>
> Prints:
> ['"."', '".."', '"cdslib_cleanup.py"', '"cadence.py"',
> '"cdsinit_cdsenv_cleanup.py"']
> ['"."', ['"cadence.py"', '"foo_cleanup.py"'], '"cdslib_cleanup.py"',
> '"cadence.py"', '"cdsinit_cdsenv_cleanup.py"']
Oh, you probably don't want those quotation marks in the parsed
strings. Change:
pp.ZeroOrMore( pp.quotedString | pp.Group(list_) ) +
to:
pp.ZeroOrMore( pp.quotedString.setParseAction(pp.removeQuotes) |
pp.Group(list_) ) +
-- Paul
More information about the Python-list
mailing list