simple parsing help

Michael J. Fromberger Michael.J.Fromberger at Clothing.Dartmouth.EDU
Sun Jul 25 13:09:24 EDT 2004


In article <e3805b94.0407240932.6d43a16b at posting.google.com>,
 steve551979 at hotmail.com (Steve) wrote:

> 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

Hello, Steve,

You've gotten a couple of answers to this already, but I'd like to offer 
another possibility, which makes use of Python's expressive iterator and 
list comprehension features:

  import re
  
  w_expr = re.compile('Winner \((\d{1,3}),\s*(\d{1,3})\)')
  
  def parse_winners(s):
    return [ ( m.group(1), m.group(2) ) for m in w_expr.finditer(s) ]

As you can see, it's concise and not too hard to read.

Cheers,
-M 

-- 
Michael J. Fromberger             | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA



More information about the Python-list mailing list