如何从日志文件中打印和汇总特定数据

时间:2014-12-12 11:27:23

标签: python logging printing sum extract

我需要一个Python脚本来分析日志文件的内容。日志文件(命名为:log.txt.2014-01-01)的组成如下:

....<different structure>

2013-05-09 19:09:20,112 [1] DEBUG Management.Handle - Action: Amount=005,00; Date=25.04.2013 19:25:04

2013-05-09 19:09:20,112 [1] DEBUG Management.Handle - Action: Amount=005,00; Date=25.04.2013 19:27:05

2013-05-09 19:09:20,112 [1] DEBUG Management.Handle - Action: Amount=005,00; Date=25.04.2013 19:28:05

...<different structure>

我需要总结Amount并打印总数。

2 个答案:

答案 0 :(得分:2)

这是regular expressions的工作:

import re
from cStringIO import StringIO

def extractAmount(file_like):
    amountRe = re.compile('^.* Management\.Handle - Action: Amount=(\d+),(\d+);')
    for line in file_like:
        result = amountRe.match(line)
        if result:
            matches = result.groups()
            yield (float(matches[0]) + (float(matches[1]) / 100.0))

data = StringIO("""....<different structure>
2013-05-09 19:09:20,112 [1] DEBUG Management.Handle - Action: Amount=005,00; Date=25.04.2013 19:25:04
2013-05-09 19:09:20,112 [1] DEBUG Management.Handle - Action: Amount=005,00; Date=25.04.2013 19:27:05
2013-05-09 19:09:20,112 [1] DEBUG Management.Handle - Action: Amount=005,00; Date=25.04.2013 19:28:05
...<different structure>""")

print sum(extractAmount(data))

在示例中,我使用了cStringIO对象来加载数据,但是这种方法应该适用于任何提供字符串的迭代(例如来自open的文件对象)。 / p>

答案 1 :(得分:0)