首页 > 解决方案 > 使用 Biopython 将多序列 fasta 蛋白质文件拆分为多个文件

问题描述

def batch_iterator(iterator, batch_size) :
    entry = True
    while entry :
        batch = []
        while len(batch) < batch_size :
            try :
                entry = iterator.__next__
            except StopIteration :
                entry = None
            if entry is None :
                #End of file
                break
            batch.append(entry)
        if batch :
            yield batch



from Bio import SeqIO

record_iter = SeqIO.parse(open("C:\\Users\\IDEAPAD\Desktop\\fypsplit\\protein.fasta"),"fasta")
for i, batch in enumerate(batch_iterator(record_iter, 1000)):
    filename = "group_%i.fasta" % (i + 1)
    with open(filename, "w") as handle:
        count = SeqIO.write(batch, handle, "fasta")
    print("Wrote %i records to %s" % (count, filename))

我正在尝试使用 Biopython 拆分 fasta 文件。在这个例子中,我想让它像 7 个文件一样。但我得到一个错误阅读AttributeError: 'function' object has no attribute 'id'

有人能帮我吗?先感谢您

标签: pythonfilesplitbiopythonfasta

解决方案


在这一行中抛出 AttributeError

count = SeqIO.write(batch, handle, "fasta")

因为SeqIO.write需要一个可迭代的或类型的列表SeqRecord。但是,您batch_iterator会生成一个方法列表。

为什么是方法?好吧,您在这里缺少一个函数调用:

entry = iterator.__next__

应该

entry = iterator.__next__()

这使得代码无错误地运行。

对于一个由 11 个序列组成的测试文件,我得到了以下结果——在将批量大小从 1000 更改为 4 以进行测试之后:

Wrote 4 records to group_1.fasta
Wrote 4 records to group_2.fasta
Wrote 3 records to group_3.fasta

推荐阅读