[英]Adding up a value after matching a line using append from a text file using python 3.x
I have a text file which contains lines as followed 我有一个文本文件,其中包含以下各行
Data_1 (2): 01 sec
Data_1 (1): 01 sec
Data_1 (1): 02 secs
Data_2 (2): 04 secs
Data_1 (3, 1, 2): 2 hrs 40 mins 02 secs
Data_2 (1): 03 secs
Data_1 (3, 1, 2): 20 secs
Data_3 (1): 02 secs
Data_3 (2): 23 secs
I want my output to be like: 我希望我的输出像:
Data_1 (2): 01 sec
Data_1 (1): 03 secs
Data_2 (2): 04 secs
Data_1 (3, 1, 2): 2 hrs 40 mins 22 secs
Just adding up the seconds if values in each line till ":" matches with each other the seconds values should be summed up irrespective of the position they are located. 如果直到“:”的每一行中的值彼此匹配,只要将秒值相加即可,无论它们位于何处,都可以将它们相加。
Code till now: 到目前为止的代码:
with open("folder/file_1", "r") as total_timing:
variable_number = len(variable_name)
evaluated_variables = []
timing = 0
for val, line in zip(range(0,variable_number),total_timing):
if variable_name[val] in line:
value = int((line.split(":")[1]).split()[0])
timing = value + timing
if variable_name[val] not in evaluated_variables:
print(" > " + variable_name[val] + " " + str(timing))
evaluated_variables.append(variable_name[val])
I have got variable_name
from another loop where I retrieve the variables. 我有variable_name
从另一个循环,我检索的变量。 But this code doesn't provide what I require. 但是这段代码没有提供我所需要的。 Any help would really great...! 任何帮助真的很棒...!
I think the easiest approach is to split each line into a name string and a time integer. 我认为最简单的方法是将每一行拆分为一个名称字符串和一个时间整数。 Then you can store the cumulative values in an ordered dict and output them once they're all added up. 然后,您可以将累积值存储在有序dict中,并在全部累加后将其输出。
from collections import OrderedDict
d = OrderedDict()
with open("folder/file_1") as file:
for line in file:
name, _, raw_time = line.rpartition(":")
time = int(raw_time.strip("sec \n"))
d[name] = d.get(name,0) + time
for name, time in d.items():
print("{}: {:02} {}".format(name, time, "sec" if time == 1 else "secs"))
Result: 结果:
Data_1 (2): 01 sec
Data_1 (1): 03 secs
Data_2 (2): 04 secs
Data_1 (3, 1, 2): 04 secs
Data_2 (1): 03 secs
Data_3 (1): 02 secs
Data_3 (2): 23 secs
#!/usr/bin/env python3
# coding: utf-8
with open("data.txt", "r") as f:
timings_totals = {}
for l in f:
key, rest = l.split(": ")
timing = int(rest.split(" ")[0])
timings_totals[key] = timings_totals.get(key, 0) + timing
for k,v in timings_totals.items():
print("{}: {} secs".format(k, v))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.