python - 使用python搜索超大文本文件

标签 python search large-data

我有一个 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}
.......

每一行都以一个数字开头,后面跟着一些其他数据。数字是按顺序排列的。我需要能够:

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

有什么有效的方法可以做到这一点而不必遍历整个文件?

最佳答案

如果你不想提前为行长度生成数据库,你可以试试这个:

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/

相关文章:

python - 如何正确实现 __str__ 和 __repr__

python - 直方图均衡化

linux - 在 Linux 中搜索文件名中的模式

mysql - 搜索非常大的彩虹表文件

jquery - 具有大型(70,000+ 项)数据集的高效 jQuery 实时搜索

python - mplfinance 是否有对数刻度设置?

Python:是在主线程中定义并从主线程或调用线程中的另一个运行中调用的函数

java - 如何用 JTable 搜索的列填充 JTextFields?

algorithm - BFS - 字链/字梯

php - 带有 "smart searching"的数据表大数据 json ,或者带有正则表达式的服务器端,或者更好的方法?