【问题标题】:Go to a specific line and read the next few in Python转到特定行并在 Python 中阅读接下来的几行
【发布时间】:2013-01-17 08:55:42
【问题描述】:

我有这个巨大的 (61GB) FASTQ 文件,我想在其中创建一个随机子集,但我无法将其加载到内存中。 FASTQ 的问题是每四行都属于一起,否则我只会创建一个随机整数列表,并且只将这些整数处的行写入我的子集文件。

到目前为止,我有这个:

import random
num = []    
while len(num) < 50000000:
    ran = random.randint(0,27000000)
    if (ran%4 == 0) and (ran not in num):
        num.append(ran)
num = sorted(num)

fastq = open("all.fastq", "r", 4)
subset = open("sub.fastq", "w")
for i,line in enumerate(fastq):
    for ran in num:
        if ran == i:
            subset.append(line)

在转到下一个随机整数之前,我不知道如何到达文件中的下三行。有人可以帮我吗?

【问题讨论】:

  • 您可以将代码的前半部分替换为random.sample

标签: python file memory line fastq


【解决方案1】:
  1. Iterate over the file in chunks of four lines.
  2. Take a random sample from that iterator.

这个想法是,您可以通过迭代并依次选择(或不选择)每个元素来从生成器中采样而无需随机访问。

【讨论】:

  • 您为迭代文件而链接的示例似乎不适用于文件。
  • @Lilith-Elina answer 适合我。你遇到了什么问题?
  • 啊,对于那个答案,我的问题是 izip_longest 既不能在我的 PC 上也不能在我们的 Linux 服务器上工作。
  • 你是从itertools导入的吗? from itertools import izip_longest 或者只是import itertools 然后itertools.izip_longest(...)
【解决方案2】:

你可以试试这个:

import random
num = sorted([random.randint(0,27000000/4)*4 for i in range(50000000/4)])

lines_to_write = 0
with open("all.fastq", "r") as fastq:
    with open("sub.fastq", "w") as subset:
        for i,line in enumerate(fastq):
            if len(num)==0:
                break
            if i == num[0]:
                num.pop(0)
                lines_to_write = 4
            if lines_to_write>0:
                lines_to_write -= 1
                subset.write(line)

【讨论】:

  • 你需要检查num是否为空。另外,i = num[0] 应该是 i == num[0]
  • 一旦 num 为空但文件还有更多行需要迭代,这不会停止并抛出错误吗?啊,我没有看到@LevLevitsky 已经提到过。
  • 你们俩都是对的。我没有尝试就完成了这段代码,很高兴你查看了它。现在它应该(希望)工作。
  • 它适用于我的小测试文件。 :-)
  • 太棒了!顺便说一句:它在 61 GB 的文件上运行多长时间?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
相关资源
最近更新 更多