如何正确拆分以下字符串? - Python

时间:2013-02-21 22:49:42

标签: python parsing

我要解析以下文件:

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']

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

3 个答案:

答案 0 :(得分:4)

您可以使用regular expression,如下所示:

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)”的行。您可以调整表达式以匹配其他行。

答案 1 :(得分:1)

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

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

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

答案 2 :(得分: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)]