Skip to content

Comment on (Python) Generator Tricks For Systems Programmer (pdf)

Comments

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)
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.