6 python 中用 string.maketrans 和 translate 巧妙替換字符串
Python實戰-從菜鳥到大牛的進階之路 作者:極客學院 投票推薦 加入書簽 留言反饋
python 中用 string.maketrans 和 trante 巧妙替換字符串
將 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://.chlinux/" "mozi/5.0 patible; 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 替換成空格
做法如下:
>>> s=''''''92.82.22.46 - - [2013-07-03t00:29:40-05:00] "get /images/mask_bg.png http/1.1" 200 195 "http://.chlinux/" "mozi/5.0 patible; msie 10.0; windows nt 6.1; wow64; trident/6.0)" "-"''''''>>> table = string.maketrans('''',''""'')>>> s.trante(table)''92.82.22.46 - - "2013-07-03t00:29:40-05:00" "get /images/mask_bg.png http/1.1" 200 195 "http://.chlinux/" "mozi/5.0 patible; msie 10.0; windows nt 6.1; wow64; trident/6.0)" "-"''>>> s.trante(table).rece(''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://.chlinux/" "mozi/5.0 patible; msie 10.0; windows nt 6.1; wow64; trident/6.0)" "-"''也可以這樣:>>> table = re.sub(''\[|\]'',''"'',s).rece(''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://.chlinux/" "mozi/5.0 patible; msie 10.0; windows nt 6.1; wow64; trident/6.0)" "-"'' </pre>
將 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://.chlinux/" "mozi/5.0 patible; 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 替換成空格
做法如下:
>>> s=''''''92.82.22.46 - - [2013-07-03t00:29:40-05:00] "get /images/mask_bg.png http/1.1" 200 195 "http://.chlinux/" "mozi/5.0 patible; msie 10.0; windows nt 6.1; wow64; trident/6.0)" "-"''''''>>> table = string.maketrans('''',''""'')>>> s.trante(table)''92.82.22.46 - - "2013-07-03t00:29:40-05:00" "get /images/mask_bg.png http/1.1" 200 195 "http://.chlinux/" "mozi/5.0 patible; msie 10.0; windows nt 6.1; wow64; trident/6.0)" "-"''>>> s.trante(table).rece(''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://.chlinux/" "mozi/5.0 patible; msie 10.0; windows nt 6.1; wow64; trident/6.0)" "-"''也可以這樣:>>> table = re.sub(''\[|\]'',''"'',s).rece(''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://.chlinux/" "mozi/5.0 patible; msie 10.0; windows nt 6.1; wow64; trident/6.0)" "-"'' </pre>