简体   繁体   English

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

[英]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.

相关问题 使用python 3.x从文本文件中找到匹配的关键字 - Finding a matching keyword from a text file using python 3.x 使用python 3.x“ with open”功能编写文本文件错误 - Writing a text file error using python 3.x “with open” function 如何使用 python 从一行中剪切文本并将 append 剪切到文本文件中的另一行? - How do you cut text from a line and append it to another line in text file using python? 通过将列表保存在文本文件中并在使用时将其导入来使用列表列表。 的Python 3.X - Using a list of lists by saving it on a text file and importing it when using it. Python 3.X 使用awk(或python)将匹配行的序列附加到文件上? - append sequences from matching lines over a file using awk (or python)? 如何使用Python 3.x使用(或更改)打印来写入文件 - How to write to a file by using (or changing) print using Python 3.x Python 3.x - 使用文本字符串作为变量名 - Python 3.x - using text string as variable name Python 2.x 到 3.x - Append 语法错误:如何使其与 Python 3.x 从 2.x 兼容。 - Python 2.x to 3.x - Append Syntaxerror: how to make it compatibale with Python 3.x from 2.x? 如何使用python 3.x在同一文件中的所有函数中使用变量值 - How to use variable value in all the functions in a same file using python 3.x 在Python 3.x中将文本文件转换为列表 - Converting a text file to a list in Python 3.x
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM