使用 python 3.x 从文本文件追加匹配行后添加一个值

Adding up a value after matching a line using append from a text file using python 3.x

我有一个文本文件,其中包含以下几行

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

我希望我的输出如下:

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

如果每行中的值直到“:”彼此匹配,则只需将秒数相加,无论它们位于何处,都应将秒值相加。

到目前为止的代码:

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])

我从另一个检索变量的循环中得到了 variable_name。但是这段代码没有提供我所需要的。任何帮助都会很棒...!

我认为最简单的方法是将每一行拆分为一个名称字符串和一个时间整数。然后你可以将累积值存储在一个有序的字典中,并在它们全部加起来后输出它们。

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"))

结果:

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