Python利用正则表达式提取文件中的数值

文章目录

前言

有时我们多次重复调用一个程序,每次调用因为输入不同,运行时间也不同,为了统计时间分布可用如下程序。

例子

假设有log文件内容如下:
Time of solve this question is : CPU : 13.4 : User : 13.1
Time of solve this question is : CPU : 12.1 : User : 12.3
Time of solve this question is : CPU : 15.3 : User : 13.4

我们想统计总时间,以及平均一个case运行的时间,则可以用如下的代码:

import re

def init():
	f = open("log")
	lines = f.readlines()
	time = 0.0
	cnt = 0
	for line in lines:
		t = re.findall(r'\d+\.?\d*', line)
		time = time + float(t[0])
		cnt = cnt + 1
	print("Total time is : ", time)
	print("The number of case : ", cnt)
	print("Average time of one case is : ", time/cnt)

if __name__ == "__main__":
	init()

程序运行结果为:

Total time is : 40.8
The number of case : 3
Average time of one case is : 13.6

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值