![](/img/trans.png)
[英]Time efficient way to skip no of line from very large text file (16gb) using python
[英]How to extract specific lines from a huge text file (>16GB) where each line starts with a string specified in another input file?
我有一个巨大的文本文件(> 16 GB大小),其中每一行都是以下形式
我必须从这个巨大的文本文件中提取所有以另一文件中指定的字符串开头的行,如下所示:
下面的代码可以完成这项工作,但问题是要花很多时间才能完成。
huge = open('huge.txt')
lines= open('lines.txt')
output = open('output','w')
X=[]
l=[]
for line1 in lines:
x1 = line1.split(',')[0].strip()
x2 = line1.split(',')[1].strip()
XX = [x1, x2]
X.append(XX)
for line3 in huge:
z1 = line3.split(',')[0].strip()
z2 = line3.split(',')[1].strip()
z3 = line3.split(',')[2].strip()
ZX = [z1, z2]
ZY = [z2, z1]
if ZX in X or ZY in X:
ZX.append(z3)
l.append(ZX)
print(ZX)
for i in l:
output.write(str(i)[1:-1]+'\n')
output.close()
Expected output:
1. 22_0F3, 33_0F4, 0.87
2. 32_2F1, 21_0F2, 0.86
我是python编程的初学者,有人可以帮助我优化此代码以快速获得结果吗?
有没有更快的方法来获得相同的输出?
将其更改为字典查找,如下所示。 您可能需要弄乱输出,因为我没有完全能力测试输出的外观,但是它应该很好地复制该功能。
huge = open('huge.txt')
lines= open('lines.txt')
output = open('output','w')
lookup_from = {}
l=[]
for line1 in lines: # if this is what you are referencing your lookups from
x1 = line1.split(',')[0].strip()
x2 = line1.split(',')[1].strip()
XX = (x1, x2) # must be a tuple to be a dictionary key instead of a list
lookup_from[XX] = 0 # assign the key to the dictionary with an arbitrary 0 value
for line3 in huge:
z1 = line3.split(',')[0].strip()
z2 = line3.split(',')[1].strip()
z3 = line3.split(',')[2].strip()
ZX = (z1, z2) # tuple again for dict
ZY = (z2, z1) # tuple
if ZX in lookup_from or ZY in lookup_from:
ZX = ZX + (z3,)
l.append(ZX)
print(ZX)
for i in l:
output.write(str(i)[1:-1]+'\n')
output.close()
预期产量:
1. 22_0F3, 33_0F4, 0.87
2. 32_2F1, 21_0F2, 0.86
另外,为了提高速度,您可以从两次查找减少到一次查找。 现在,您正在检查(X,Y)和(Y,X),但您始终可以按特定顺序(按字母顺序)进行查找,然后始终也使用该顺序进行查找。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.