simple parsing help
ptmcg at austin.rr._bogus_.com
Sun Jul 25 03:11:14 CEST 2004
"Steve" <steve551979 at hotmail.com> wrote in message
news:e3805b94.0407240932.6d43a16b at posting.google.com...
> I have a string that looks kinda like "Winner (121,10) blah blah blah
> Winner (10,400) blah blah Winner (103,4) blah blah..."
> I just want to extract the coordinate parts of the string (xxx,xxx)
> which could be 1-3 characters and put them into an array ideally.
> What is the easiest way to do this in Python? Can anyone provide a
> simple line or two of code to help me get started?
> Thanks very much,
Here's a pyparsing version, which will be slower than re's, but perhaps a
bit more readable.
Download pyparsing at http://pyparsing.sourceforge.net.
from pyparsing import Word, nums, delimitedList, Suppress
testdata = "Winner (121,10) blah blah blah Winner (10,400) blah blah Winner
(103,4) blah blah"
num = Word(nums)
coord = Suppress("(") + num + Suppress(",") + num + Suppress(")")
for t,s,e in coord.scanString(testdata):
Or if you like, add this line just before the for statement to do
conversions to int as well:
coord.setParseAction( lambda s,l,t: map(int,t) )
Now change 'print t' to 'print "x=%d, y=%d" % tuple(t)' and you'll get:
More information about the Python-list