本文共 1503 字,大约阅读时间需要 5 分钟。
python中用string.maketrans和translate巧妙替换字符串
将nginx日志中字符串 [2013-07-03T00:29:40-05:00] HTTP 格式化为:"2013-07-03 00:29:40-05:00"
整条日志如下:
92.82.22.46 - - [2013-07-03T00:29:40-05:00] "GET /images/mask_bg.png HTTP/1.1" 200 195 "http://www.chlinux.net/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"
将[2013-07-03T00:29:40-05:00] 替换成为:"2013-07-03 00:29:40-05:00"
把[]换成"",然后把T替换成空格
做法如下:
1 2 3 4 5 6 7 8 9 10 | >>> s = '''92.82.22.46 - - [2013-07-03T00:29:40-05:00] "GET /images/mask_bg.png HTTP/1.1" 200 195 "http://www.chlinux.net/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"''' >>> table = string.maketrans( '[]' , '""' ) >>> s.translate(table) '92.82.22.46 - - "2013-07-03T00:29:40-05:00" "GET /images/mask_bg.png HTTP/1.1" 200 195 "http://www.chlinux.net/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"' >>> s.translate(table).replace( 'T' , ' ' , 1 ) #替换掉第一个T为空格 '92.82.22.46 - - "2013-07-03 00:29:40-05:00" "GET /images/mask_bg.png HTTP/1.1" 200 195 "http://www.chlinux.net/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"' 也可以这样: >>> table = re.sub( '\[|\]' , '"' ,s).replace( 'T' , ' ' , 1 ) >>> print table '92.82.22.46 - - "2013-07-03 00:29:40-05:00" "GET /images/mask_bg.png HTTP/1.1" 200 195 "http://www.chlinux.net/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"' 本文转自 lover00751CTO博客,原文链接:http://blog.51cto.com/wangwei007/1242206,如需转载请自行联系原作者 |