News for hackers. Stuff that matters.
Re: (Python) Generator Tricks For Systems Programmer (pdf) by julian37 on Wednesday December 14, 2011 @05:23AM (#3351333)
An alternate (and, arguably, more elegant) approach to "Parsing with Regex" and "Tuples to Dictionaries" is to use named regex groups and the MatchObject's "groupdict" method like so:

  logpats = r'(?P<host>\S+) (?P<referrer>\S+) (?P<user>\S+) \[(?P<datetime>.*?)\] '\
            r'"(?P<method>\S+) (?P<request>\S+) (?P<proto>\S+)" (?P<status>\S+) '\
            r'(?P<bytes>\S+)'
  logpat  = re.compile(logpats)
  groups  = (logpat.match(line) for line in loglines)
  log     = (g.groupdict() for g in groups if g)

There are no comments on this comment yet.