1

我有一个序列信息文件,所以文件的结构是这样的,

[SEQUENCE ID]
atgctagctagatcga
[SEQUENCE ID]
agatcgatggctagatc

我一直在做的是比较文件以查看共享哪些序列 ID,这很简单,但现在我想提取与 ID 关联的实际序列。我使用的文件很大(10 GB+),所以使用字典或任何涉及将所有行读入系统内存的东西都用完了。

基本上,代码的目的是如果文件 1 中的序列 ID 在文件 2 中找不到,则返回文件 1 中序列 ID 之后的行。有什么提示吗?

4

3 回答 3

2

所以你只需要第N行和第N+1行?在这种情况下,分两行读取文件。然后,您始终可以访问序列 ID 和序列。

from itertools import izip
with open('data.txt', 'r') as f:
    for line1, line2 in izip(*(iter(f),) * 2):
        print line1, line2
于 2013-02-18T12:13:20.977 回答
0

简短的回答:您将不得不使用第三方 Python 库来保持其中一个数据序列的可搜索性优于 O(n)。

如果它们未排序,则必须至少对其中一个文件进行排序。可以这样想:我从文件 1 中获取序列 ID - 并检查它是否不存在于文件 2 中,我必须读取所有文件 - 比读取文件一次更不可行。

比 - 比排序更好,拥有一个可以将排序数据保存在磁盘上以提供快速搜索并且仍然能够增长的数据结构会很有用 - 这也将有助于排序,就像你们所有人一样第一步要做的是读取文件 2 中的条目,然后将其插入到这个增长排序的磁盘持久数据结构中。

虽然您当然可以滚动您自己的数据结构来执行此操作,但我建议使用ZODB - ZOPE 的面向对象的 DATABSe,带有 btree 文件夹,并将您的“2 行数据”制作成您任务的最小对象。

于 2013-02-18T12:24:43.587 回答
0

假设 [SEQUENCE ID] 确实适合内存,并且您的大部分数据实际上在序列行上(与提供的示例不同)-您可以选择解析文件(您的问题中的 file2),并且注释不仅 te [SEQUENCE ID] - 但每个此类标识符的文件位置。这种方法可以让您在不中断当前工作流程的情况下继续进行(例如,必须了解数据库):

def get_indexes(filename):
    with open(filename, "rt") as file:
        sequences = {}
        while True:
            position = file.tell()
            id = file.readline()
            if not id:
                break()
            sequences[id.strip()] = position
            # skip corresponding data line:
            file.readline()
    return sequences

def fetcher(filename1, filename2, sequences):
    with open(filename1, "rt") as file1, open(filename2, "rt" as file2):
        while True:
            id = file.readline()
            data = file.readline()
            if not id:
                break
            id = id.strip()
            if id in sequences:
                # postion file2 reading at the identifier:
                file2.seek(sequences[id])
                # throw away id:
                file2.readline()
                data = file.readline()

            yield id, data

if __name__== "__main__":
    sequences = getindexes("/data/file2")
    for id, data in fetcher("/data/file1", "/data/file2", sequences):
        print "%s\n%s"% (id, data)
于 2013-02-18T13:16:19.087 回答