simple parsing help

Paul McGuire 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...
> Hi,
>
> 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,
>
> Steve
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.
-- Paul


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):
    print t

gives:
['121', '10']
['10', '400']
['103', '4']


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) )

Giving:

[121, 10]
[10, 400]
[103, 4]

Now change 'print t' to 'print "x=%d, y=%d" % tuple(t)' and you'll get:
x=121, y=10
x=10, y=400
x=103, y=4


Have fun!





More information about the Python-list mailing list