我在名为
的文本文件中有以下数据表示形式数据.txt
03/05/2016 11:00 50
03/05/2016 11:10 10
03/05/2016 11:20 30
03/05/2016 11:30 40
03/05/2016 11:40 40
03/05/2016 11:50 50
03/05/2016 11:60 70
03/05/2016 12:00 25
03/05/2016 12:10 69
03/05/2016 12:20 25
03/05/2016 12:30 59
03/05/2016 12:40 25
03/05/2016 12:50 29
03/05/2016 12:60 25
我想执行某些数学运算,以便获得最终结果
03/05/2016 11:00 - 12:00 290
03/05/2016 12:00 - 13:00 257
此结果存储在另一个文本文件(例如 data1.txt)中
这里290是11:00到12:00的数据总和,257是12:00到13:00的数据总和
我想用 python 2.7 编写这段代码
我怎样才能做到这一点......
**UPDATED**
import time
import datetime
while 1:
final_sensorvalue = 0
st_time = time.time()
crntdatetime = 0.0
while ((time.time() - st_time) < 600.0):
sensorvalue = 10 # read sensor value
final_sensorvalue = final_sensorvalue + sensorvalue
time.sleep(2)
f = open('data.txt','a')
crntdatetime = datetime.datetime.now()
timestamp = crntdatetime.strftime("%d/%m/%Y %H:%M")
outstring = str(timestamp)+" "+str(final_sensorvalue)+ "\n"
print outstring
f.write(outstring)
f.close()
time.sleep(2)
最佳答案
您可以将这些行转换为 Counter
键为日期和时间 ('03/05/2016 11'
) 且值为 int
的对象。然后,您可以将所有 Counter
对象添加在一起,对项目进行排序并将它们写入文件:
from collections import Counter
import re
with open('test.txt') as f:
res = sum((Counter({x.group(1): int(x.group(2))})
for x in (re.search('(.*?):.*\s(\d+)', line) for line in f) if x),
Counter())
with open('output.txt', 'w') as f:
f.writelines('{0}:00 - {1}:00 {2}\n'.format(k, int(k.split()[-1]) + 1, v)
for k, v in sorted(res.iteritems()))
output.txt
的内容:
03/05/2016 11:00 - 12:00 290
03/05/2016 12:00 - 13:00 257
关于python - 使用python进行数据提取及其求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37000739/