美文网首页
python生成器-管道学习(四)

python生成器-管道学习(四)

作者: frankie_cheung | 来源:发表于2019-07-13 13:05 被阅读0次

这个作者和服务器日志杠上了,第四部分是格式化日志信息输出,
需求:
服务器请求日志 需要格式化成如下格式:
host referrer user [datetime] "request" status bytes

使用正则,把每一行日志进行格式化:

logpats = r'(\S+) (\S+) (\S+) \[(.*?)\] '\
           r'"(\S+) (\S+) (\S+)" (\S+) (\S+)'
logpat = re.compile(logpats)
groups = (logpat.match(line) for line in loglines)
tuples = (g.groups() for g in groups if g)

tuples 是元祖形式,然后作者比比了一顿 他多么的不喜欢元祖,他喜欢字典,
tuples里面每个值是如下形式:

('71.201.176.194', '-', '-', '26/Feb/2008:10:30:08 -0600','GET', '/ply/ply.html', 'HTTP/1.1', '200', '97238')

作者使用zip函数加dict把生成器的每个元素转为字典形式,这个操作我觉得还是很惊艳的:

colnames = ('host','referrer','user','datetime',
 'method','request','proto','status','bytes')
log = (dict(zip(colnames, t)) for t in tuples)

用类似于map函数的方法对字段进行转换:

def field_map(dictseq, name, func):
     for d in dictseq:
         d[name] = func(d[name])
         yield d

log = field_map(log, "status", int)
log = field_map(log, "bytes",lambda s: int(s) if s !='-' else 0)

这样log里面每个字典的status就是int类型了,没有字节的'_',转为0

相关文章

网友评论

      本文标题:python生成器-管道学习(四)

      本文链接:https://www.haomeiwen.com/subject/raipkctx.html