解析数组内容并添加值

2024-09-30 08:26:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个文件以“.log”结尾。最后三行包含感兴趣的数据

示例文件内容(最后四行)。第四行为空):

总计:150

成功:120

错误:30

我将这些内容读入一个数组,并试图找到一种优雅的方法: 1) 提取每个类别的数字数据(总计、成功、错误)。如果第二部分中没有数字数据,则出错 2) 把它们都加起来

我编写了以下代码(为了简洁起见,排除了getLastXLines函数)返回聚合:

def getSummaryData(testLogFolder):
    (path, dirs, files) = os.walk(testLogFolder).next()
    #aggregate = [grandTotal, successTotal, errorTotal]
    aggregate = [0, 0, 0]
    for currentFile in files:
            fullNameFile = path + "\\" + currentFile
            if currentFile.endswith(".log"):
                with open(fullNameFile,"r") as fH:
                    linesOfInterest=getLastXLines(fH, 4)
                #If the file doesn't contain expected number of lines
                if len(linesOfInterest) != 4:
                    print fullNameFile + " doesn't contain the expected summary data"
                else:
                    for count, line in enumerate(linesOfInterest[0:-1]):
                        results = line.split(': ')
                        if len(results)==2:
                            aggregate[count] += int(results[1])
                        else:
                            print "error with " + fullNameFile + " data. Not adding the total"

    return aggregate

作为python的新手,看到python的强大功能,我觉得有一种更强大、更高效的方法可以做到这一点。可能有一个简短的清单来做这种事情?请帮忙


Tags: 文件the数据方法log内容if错误
1条回答
网友
1楼 · 发布于 2024-09-30 08:26:12
def getSummaryData(testLogFolder):
    summary = {'Total':0, 'Success':0, 'Error':0}
    (path, dirs, files) = os.walk(testLogFolder).next()
    for currentFile in files:
            fullNameFile = path + "\\" + currentFile
            if currentFile.endswith(".log"):
                with open(fullNameFile,"r") as fH:
                    for pair in [line.split(':') for line in fH.read().split('\n')[-5:-2]]:
                        try:
                            summary[pair[0].strip()] += int(pair[1].strip())
                        except ValueError:
                            print pair[1] + ' is not a number'
                        except KeyError:
                            print pair[0] + ' is not "Total", "Success", or "Error"'
    return summary

佩斯作品:

fH.read().split('\n')[-5:-2]

这里我们取最后4行,除了文件的最后一行

line.split(':') for line in

从这些线,我们打破了结肠

try:
    summary[pair[0].strip()] += int(pair[1].strip())

现在我们试着从第二个得到一个数字,从第一个得到一个键,然后加到总数中

except ValueError:
    print pair[1] + ' is not a number'
except KeyError:
    print pair[0] + ' is not "Total", "Success", or "Error"'

如果我们发现了一个不是数字的东西,或者一个不是我们要找的钥匙,我们就会打印一个错误

相关问题 更多 >

    热门问题