【问题标题】:Pick the values from specific lines of a log file and calculate an average从日志文件的特定行中选择值并计算平均值
【发布时间】:2019-09-16 14:50:21
【问题描述】:

伙计们, 我有一个看起来像这样的日志文件

Input image filename:(416, 416, 3)
Found 3 boxes for img
Inference time : 3.100685347104464 
traffic light 0.85 
traffic light 0.96 
traffic light 0.98 
Input image filename:(416, 416, 3)
Found 3 boxes for img
Inference time : 2.0816197767817197 
traffic light 0.90 
traffic light 0.92 
Input image filename:(416, 416, 3)
Found 3 boxes for img
Inference time : 2.0610929683485253 
traffic light 0.82 
traffic light 0.96 
traffic light 0.99 

我想编写一个循环,将“推理时间..”和“输入图像文件名..”行之间的交通灯值相加并计算平均值。
例如:
第一部分:(0.85+0.96+0.98)/3 = 0.93
第二部分:(0.90+0.92)/2 = 0.91
第三部分:(0.82+0.96+0.99)/3 = 0.93

返回值:(0.93, 0.91, 0.93)

到目前为止,我只能读取找到“交通灯”字样的行中的所有值。

import os 
log_path  = "data/test.log"

accuracy_lines = []
accuracy = [] 

for line_acc in open(log): 
    if 'traffic light ' in line_acc: 
        accuracy_lines.append(line_acc)

for n in range(len(accuracy_lines)):
    lineParts = accuracy_lines[n].split(',')
    accuracy.append(float(lineParts[0].split()[2]))
print(accuracy)

很遗憾,我不知道如何继续。 如果你能帮助我,我会很高兴。

许多问候

【问题讨论】:

    标签: python loops


    【解决方案1】:

    使用以下方法:

    log_path  = "data/test.log"
    
    with open(log_path) as f:
        numbers, res = [], []
        for line in f:
            if line.startswith('traffic light'):
                numbers.append(float(line.split()[-1]))
            elif line.startswith('Input image filename') and numbers:
                res.append(sum(numbers) / (len(numbers)))
                numbers.clear()
        if numbers: res.append(sum(numbers) / len(numbers))  # capturing trailing numbers
        print(res)
    

    输出:

    [0.93, 0.91, 0.9233333333333332]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 2023-03-21
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      相关资源
      最近更新 更多