我有一个 4000 万行、3 GB 的文本文件(可能无法放入内存),格式如下:
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}
.......
每一行都以一个数字开头,后面跟着一些其他数据。数字是按顺序排列的。我需要能够:
- 给定一个数字
x
和一个范围y
, 找出编号在y
内的所有行x
的范围.例如,如果x=20
和y=5
, 我需要找到编号在15
之间的所有行和25
. - 将这些行存储到另一个单独的文件中。
有什么有效的方法可以做到这一点而不必遍历整个文件?
最佳答案
如果你不想提前为行长度生成数据库,你可以试试这个:
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
它首先对文件执行二进制搜索,直到接近(小于 maxRowOffset
)要查找的行。然后它开始读取每一行,直到找到大于 x-y
的行。该行以及它之后的每一行都被写入输出文件,直到找到大于 x+y
的行,然后程序退出。
我在一个 1,000,000 行的文件上测试了它,它运行了 0.05 秒。将此与阅读每一行花费 3.8 秒进行比较。
关于python - 使用python搜索超大文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12859488/