best way to parse a function-call-like string?
John Machin
sjmachin at lexicon.net
Thu Feb 26 17:02:53 EST 2009
On Feb 27, 8:29 am, m... at pixar.com wrote:
> I have some strings that look like function calls, e.g.
>
> "junkpkg.f1"
> "junkpkg.f1()"
> "junkpkg.f1('aaa')"
> "junkpkg.f1('aaa','bbb')"
> "junkpkg.f1('aaa','bbb','ccc')"
> "junkpkg.f1('aaa','with,comma')"
Examples are better than no examples, but a grammar would be a great
help. What about
"junkpkg.f1('aaa','with)parenthesis')"
"junkpkg.f1('aaa','with''ONEapostrophe')"
>
> and I need to split them into the function name and list of parms, e.g.
>
> "junkpkg.f1", []
> "junkpkg.f1", []
> "junkpkg.f1", ['aaa']
> "junkpkg.f1", ['aaa','bbb']
> "junkpkg.f1", ['aaa','bbb','ccc']
> "junkpkg.f1", ['aaa','with,comma']
>
> What's the best way to do this? I would be interested in either
> of two approaches:
>
> - a "real" way which comprehensively
>
> - a quick-and-dirty way which handles most cases, so that I
> can get my coding partner running quickly while I do the
> "real" way. will the csv module do the right thing for
> the parm list?
It should, for "most cases". Any reason you can't try it out for
yourself?
It appears to "work" in the sense that if you have isolated a string
containing the parameters, the csv module can be used to "parse" it:
| Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit
(Intel)] on win32
| Type "help", "copyright", "credits" or "license" for more
information.
| >>> import csv, cStringIO
| >>> argstring = "'aaa','with,comma'"
| >>> csvargs = lambda s: list(csv.reader(cStringIO.StringIO(s),
quotechar="'"))
| >>> csvargs(argstring)
| [['aaa', 'with,comma']]
| >>> csvargs("'aaa','with''ONEapostrophe'")
| [['aaa', "with'ONEapostrophe"]]
| >>>
HTH
John
More information about the Python-list
mailing list