1

我有以下文件要解析:

Total Virtual Clients       :             10      (1 Machines)
Current Connections         :             10
Total Elapsed Time          :             50 Secs (0 Hrs,0 Mins,50 Secs)

Total Requests              :         337827      (    6687/Sec)
Total Responses             :         337830      (    6687/Sec)
Total Bytes                 :      990388848      (   20571 KB/Sec)
Total Success Connections   :           3346      (      66/Sec)
Total Connect Errors        :              0      (       0/Sec)
Total Socket Errors         :              0      (       0/Sec)
Total I/O Errors            :              0      (       0/Sec)
Total 200 OK                :          33864      (     718/Sec)
Total 30X Redirect          :              0      (       0/Sec)
Total 304 Not Modified      :              0      (       0/Sec)
Total 404 Not Found         :         303966      (    5969/Sec)
Total 500 Server Error      :              0      (       0/Sec)
Total Bad Status            :         303966      (    5969/Sec)

所以我有解析算法来搜索这些值的文件,但是,当我这样做时:

for data in temp:
     line = data.strip().split()
     print line

我的临时缓冲区在哪里temp,其中包含这些值,我得到:

['Total', 'I/O', 'Errors', ':', '0', '(', '0/Sec)']
['Total', '200', 'OK', ':', '69807', '(', '864/Sec)']
['Total', '30X', 'Redirect', ':', '0', '(', '0/Sec)']
['Total', '304', 'Not', 'Modified', ':', '0', '(', '0/Sec)']
['Total', '404', 'Not', 'Found', ':', '420953', '(', '5289/Sec)']
['Total', '500', 'Server', 'Error', ':', '0', '(', '0/Sec)']

我想要:

['Total I/O Errors', '0', '0']
['Total 200 OK', '69807', '864']
['Total 30X Redirect', '0', '0']

等等。我怎么能做到这一点?

4

3 回答 3

4

您可以使用正则表达式,如下所示:

import re
rex = re.compile('([^:]+\S)\s*:\s*(\d+)\s*\(\s*(\d+)/Sec\)')
for line in temp:
    match = rex.match(line)
    if match:
        print match.groups()

这会给你:

['Total Requests', '337827', '6687']
['Total Responses', '337830', '6687']
['Total Success Connections', '3346', '66']
['Total Connect Errors', '0', '0']
['Total Socket Errors', '0', '0']
['Total I/O Errors', '0', '0']
['Total 200 OK', '33864', '718']
['Total 30X Redirect', '0', '0']
['Total 304 Not Modified', '0', '0']
['Total 404 Not Found', '303966', '5969']
['Total 500 Server Error', '0', '0']
['Total Bad Status', '303966', '5969']

请注意,这只会匹配对应于“TITLE:NUMBER(NUMBER/Sec)”的行。您也可以调整表达式以匹配其他行。

于 2013-02-21T22:58:09.683 回答
1

正则表达式对于解析数据来说太过分了,但它是表达固定长度字段的便捷方式。例如

for data in temp:
    first, second, third = re.match("(.{28}):(.{21})(.*)", data).groups()
    ...

这意味着第一个字段是 28 个字符。跳过':',接下来的 21 个字符是第二个字段,其余的是第三个字段

于 2013-02-21T23:09:46.763 回答
0

您需要根据格式中的其他分隔符进行拆分,而不是在空格上拆分,它可能看起来像这样:

for data in temp:
     first, rest = data.split(':')
     second, rest = rest.split('(')
     third, rest = rest.split(')')
     print [x.strip() for x in (first, second, third)]
于 2013-02-21T23:01:01.820 回答