如何从一个巨大的文本文件(>16GB)中提取特定的行,其中每一行都以另一个输入文件中指定的字符串开头?

2024-04-19 04:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个巨大的文本文件>;16 GB大小),其中每行的格式为

  1. 22英尺3,33英尺4,0.87
  2. 28英尺3,37英尺4,0.79
  3. 。。。。。。。。。。。。。。。。。。。。 . . .
  4. 21英寸,32英寸,0.86英寸

我必须从这个巨大的文本文件中提取所有以另一个文件中指定的字符串开头的行

  1. 22层,33层
  2. 32英尺1,21英尺2
  3. 。。。。。。。。。。。。。。 . .

下面的代码可以完成这项工作,但问题是它需要很多时间才能完成

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编程的初学者,有人能帮我优化一下代码以快速得到结果吗

有没有更快的方法来获得相同的输出


Tags: inforoutputopensplitstriplineszx
1条回答
网友
1楼 · 发布于 2024-04-19 04:31:42

将其更改为字典查找,如下所示。您可能需要稍微弄乱输出,因为我没有完全的能力来测试它的外观,但它应该可以很好地复制函数

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),但是您可以始终按照特定的顺序(可能是按字母顺序)进行查找,然后始终使用该顺序进行查找

相关问题 更多 >