gpt4 book ai didi

python - 逐行处理非常大 (>20GB) 的文本文件

转载 作者:IT老高 更新时间:2023-10-28 21:37:31 26 4
gpt4 key购买 nike

我有许多非常大的文本文件需要处理,最大的大约 60GB。

每行在七个字段中有 54 个字符,我想从前三个字段中的每个字段中删除最后三个字符 - 这应该会减少大约 20% 的文件大小。

我是 Python 的新手,我有一个代码可以以每小时 3.4 GB 的速度完成我想做的事情,但要成为一项有值(value)的练习,我确实需要至少 10 GB/小时 - 有没有加快速度的方法?这段代码并没有接近挑战我的处理器,所以我猜测它受到内部硬盘驱动器读写速度的限制?

def ProcessLargeTextFile():
r = open("filepath", "r")
w = open("filepath", "w")
l = r.readline()
while l:
x = l.split(' ')[0]
y = l.split(' ')[1]
z = l.split(' ')[2]
w.write(l.replace(x,x[:-3]).replace(y,y[:-3]).replace(z,z[:-3]))
l = r.readline()
r.close()
w.close()

任何帮助将不胜感激。我在 Windows 7 上使用 IDLE Python GUI 并拥有 16GB 内存 - 也许不同的操作系统会更高效?

编辑:这是要处理的文件的摘录。

70700.642014 31207.277115 -0.054123 -1585 255 255 255
70512.301468 31227.990799 -0.255600 -1655 155 158 158
70515.727097 31223.828659 -0.066727 -1734 191 187 180
70566.756699 31217.065598 -0.205673 -1727 254 255 255
70566.695938 31218.030807 -0.047928 -1689 249 251 249
70536.117874 31227.837662 -0.033096 -1548 251 252 252
70536.773270 31212.970322 -0.115891 -1434 155 158 163
70533.530777 31215.270828 -0.154770 -1550 148 152 156
70533.555923 31215.341599 -0.138809 -1480 150 154 158

最佳答案

这样写你的代码更惯用

def ProcessLargeTextFile():
with open("filepath", "r") as r, open("outfilepath", "w") as w:
for line in r:
x, y, z = line.split(' ')[:3]
w.write(line.replace(x,x[:-3]).replace(y,y[:-3]).replace(z,z[:-3]))

这里的主要节省是只执行一次 split,但如果 CPU 没有被征税,这可能几乎没有什么区别

可能有助于一次保存几千行并将它们写入一次以减少硬盘驱动器的抖动。一百万行只有 54MB 的 RAM!

def ProcessLargeTextFile():
bunchsize = 1000000 # Experiment with different sizes
bunch = []
with open("filepath", "r") as r, open("outfilepath", "w") as w:
for line in r:
x, y, z = line.split(' ')[:3]
bunch.append(line.replace(x,x[:-3]).replace(y,y[:-3]).replace(z,z[:-3]))
if len(bunch) == bunchsize:
w.writelines(bunch)
bunch = []
w.writelines(bunch)

@Janne 建议,另一种生成线条的方法

def ProcessLargeTextFile():
bunchsize = 1000000 # Experiment with different sizes
bunch = []
with open("filepath", "r") as r, open("outfilepath", "w") as w:
for line in r:
x, y, z, rest = line.split(' ', 3)
bunch.append(' '.join((x[:-3], y[:-3], z[:-3], rest)))
if len(bunch) == bunchsize:
w.writelines(bunch)
bunch = []
w.writelines(bunch)

关于python - 逐行处理非常大 (>20GB) 的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16669428/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com