我需要一个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
并打印总数。
答案 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)
import re
x=<your_test_string>
z= [float(re.sub(r",",".",i)) for i in re.findall(r"(?<=DEBUG Management\.Handle - Action: Amount=)([^;]+)",x)]
print sum(z)
你可以试试这个。
尝试