使用python搜索极大的文本文件

Loc*_*sta 3 python search large-data

我有一个4000万行,3千兆字节的文本文件(可能无法适应内存),格式如下:

399.4540176 {Some other data}
404.498759292 {Some other data}
408.362737492 {Some other data}
412.832976111 {Some other data}
415.70665675 {Some other data}
419.586515381 {Some other data}
427.316825959 {Some other data}
.......
Run Code Online (Sandbox Code Playgroud)

每行以数字开头,后跟一些其他数据.数字按排序顺序排列.我需要能够:

  1. 给定一个数字x和一个范围y,找到其数量在y范围内的所有行x.例如,如果x=20y=5,我需要找到其数量介于15和之间的所有行25.
  2. 将这些行存储到另一个单独的文件中

在不必遍历整个文件的情况下,这样做的有效方法是什么?

Mat*_*att 5

如果您不想提前为行长度生成数据库,可以尝试这样做:

import os
import sys

# Configuration, change these to suit your needs
maxRowOffset = 100  #increase this if some lines are being missed
fileName = 'longFile.txt'
x = 2000
y = 25

#seek to first character c before the current position
def seekTo(f,c):
    while f.read(1) != c:
        f.seek(-2,1)

def parseRow(row):
    return (int(row.split(None,1)[0]),row)

minRow = x - y
maxRow = x + y
step = os.path.getsize(fileName)/2.
with open(fileName,'r') as f:
    while True:
        f.seek(int(step),1)
        seekTo(f,'\n')
        row = parseRow(f.readline())
        if row[0] < minRow:
            if minRow - row[0] < maxRowOffset:
                with open('outputFile.txt','w') as fo:
                    for row in f:
                        row = parseRow(row)
                        if row[0] > maxRow:
                            sys.exit()
                        if row[0] >= minRow:
                            fo.write(row[1])
            else:
                step /= 2.
                step = step * -1 if step < 0 else step
        else:
            step /= 2.
            step = step * -1 if step > 0 else step
Run Code Online (Sandbox Code Playgroud)

它首先对文件执行二进制搜索,直到它接近(小于maxRowOffset)要查找的行.然后它开始读取每一行,直到找到一个大于x-y.该行以及它之后的每一行都被写入输出文件,直到找到大于该行的行x+y,以及程序退出的那一行.

我在1,000,000行文件上对此进行了测试,并在0.05秒内运行.相比之下,读取每条花了3.8秒.