我有一个工作脚本,可以从一系列巨大的文本文件中提取某些数据。不幸的是,我走了“ readlines”的路线,因此,在处理了一定数量的文件之后,我的代码内存不足。

我试图重新编写代码,以使用“ for file in file”格式逐行处理文件,但是一旦找到字符串,我的行处理就会出现问题。

基本上,一旦找到我的字符串,我希望转到文本文件中的各个周围行,因此我希望回到之前的16行(以及10行和4行),并进行一些行处理以收集一些与搜索相关的数据线。通过readlines路由,我枚举了文件,但我正在努力逐行找出正确的方法(或者甚至找出是否有可能!)。

这是我的代码,我承认那里有一些错误的代码,因为我在抓线过程中玩了一些,基本上是在[-xx]部分附近...

searchstringsFilter1 = ['Filter Used          : 1']


with open(file, 'r') as f:
    for line in f:

        timestampline = None
        timestamp = None

        for word in searchstringsFilter1:
            if word in line:
                #print line
                timestampline = line[-16]
                #print timestampline
                keyline = line
                Rline = line[-10]
                print Rline

                Rline = re.sub('[()]', '', Rline)
                SNline = line[-4]
                SNline = re.sub('[()]', '', SNline)

                split = keyline.split()
                str = timestampline
                match = re.search(r'\d{2}:\d{2}:\d{2}.\d{3}', str)
                valueR = Rline.split()
                valueSN = SNline.split()

                split = line.split()

                worksheetFilter.write(row_num,0,match.group())
                worksheetFilter.write(row_num,1,split[3], integer_format)
                worksheetFilter.write(row_num,2,valueR[4], decimal_format)
                worksheetFilter.write(row_num,3,valueSN[3], decimal_format)
                row_num+=1
                tot = tot+1
                break

    print 'total count for', '"',searchstringsFilter1[a],'"', 'is', tot
    Filtertot = tot
    tot = 0


有什么明显的地方我做错了,还是我遵循一条完全错误的道路去做我想做的事情?

非常感谢您阅读本文,
米克

最佳答案

您需要circular buffer暂时将前一行保留在内存中。这可以使用collections.deque获得:

import collections

ring_buf = collections.deque(maxlen=17)

with open(file, 'r') as f:
    for line in f:
        ring_buf.append([line]) # append the new line and overwrite the last one
                              # FIFO style

        timestampline = None
        timestamp = None

        for word in searchstringsFilter1:
            if word in line:
                #print line
                timestampline = ring_buf[-16]
                #print timestampline
                keyline = line
                Rline = ring_buf[-10]
                print Rline

                Rline = re.sub('[()]', '', Rline)
                SNline = ring_buf[-4]
                SNline = re.sub('[()]', '', SNline)

关于python - 使用Python将我的代码从“readlines”重写为“for line in file”格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25741026/

10-12 16:51
查看更多