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

标签 python python-2.7 logic

我在名为

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

数据.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/

相关文章:

python - 如何在Python中每个等级后插入3个空行

c++ - 强制执行所有&&?

c - 如何根据成员的值对结构实例进行排序

python - 如何将两个列表作为值插入字典的同一键

python - 更改后重新加载模块

python - 如何将此字典转换为元组列表?

.net - 逻辑帮助,可能与循环有关

python - 如何在 python 中打印退格键的字符串版本?

python - 不间断的 nginx + 2 gunicorns 设置

python - 如何将新的键值对添加到字典中,其中值是数组的数组