使用python进行数据提取及其求和

时间:2016-05-03 09:43:11

标签: python python-2.7 logic

我在一个名为

的文本文件中有以下数据表示

data.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)

2 个答案:

答案 0 :(得分:1)

您可以尝试这样:

fo = open("data.txt","r")
lines = fo.readlines()
#print lines
d={}

for i in range(0,len(lines),2):
    l = lines[i].split()
    if int(l[1].split(":")[0]) != 23:
        time = l[1].split(":")[0] + ":00-" + str(int(l[1].split(":")[0])+1) +":00"
    else:
        time = l[1].split(":")[0] + ":00-0:00"
    #key = l[0]+"_"+l[1].split(":")[0]
    key = l[0]+"_"+time
    if key in d:
        d[key] = int(d[key]) + int(l[2])
    else:
        d[key] = int(l[2])
print d


>>> 
{'03/05/2016_11:00-12:00': 290, '03/05/2016_12:00-13:00': 257}

答案 1 :(得分:1)

您可以将这些行转换为Counter个对象,其中键是日期&amp;小时('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