解析数组内容并添加值

时间:2014-09-12 23:11:18

标签: python arrays python-2.7 list-comprehension

我有几个文件以" .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来说相对较新,并且看到它的强大功能,我觉得可能有更强大有效的方法来实现这一点。可能有一个短名单理解来做这种事情?请帮忙。

1 个答案:

答案 0 :(得分:1)

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

by peice:

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

如果我们发现一些不是数字或某个不是我们要找的密钥,我们就会打印错误