我应该首先说我对 Python 和 Biopython 都是新手。我正在尝试将一个大的 .fasta 文件(包含多个条目)拆分为单个文件,每个文件都有一个条目。我在 Biopython wiki/Cookbook 网站上找到了以下大部分代码,并对其进行了一些调整。我的问题是这个生成器将它们命名为“1.fasta”、“2.fasta”等,我需要用一些标识符来命名它们,例如 GI 编号。
def batch_iterator(iterator, batch_size) :
"""Returns lists of length batch_size.
This can be used on any iterator, for example to batch up
SeqRecord objects from Bio.SeqIO.parse(...), or to batch
Alignment objects from Bio.AlignIO.parse(...), or simply
lines from a file handle.
This is a generator function, and it returns lists of the
entries from the supplied iterator. Each list will have
batch_size entries, although the final list may be shorter.
"""
entry = True #Make sure we loop once
while entry :
batch = []
while len(batch) < batch_size :
try :
entry = next(iterator)
except StopIteration :
entry = None
if entry is None :
#End of file
break
batch.append(entry)
if batch :
yield batch
from Bio import SeqIO
infile = input('Which .fasta file would you like to open? ')
record_iter = SeqIO.parse(open(infile), "fasta")
for i, batch in enumerate(batch_iterator(record_iter, 1)) :
outfile = "c:\python32\myfiles\%i.fasta" % (i+1)
handle = open(outfile, "w")
count = SeqIO.write(batch, handle, "fasta")
handle.close()
如果我尝试更换:
outfile = "c:\python32\myfiles\%i.fasta" % (i+1)
和:
outfile = "c:\python32\myfiles\%s.fasta" % (record_iter.id)
所以它会在 SeqIO 中命名类似于 seq_record.id 的东西,它会给出以下错误:
Traceback (most recent call last):
File "C:\Python32\myscripts\generator.py", line 33, in [HTML]
outfile = "c:\python32\myfiles\%s.fasta" % (record_iter.id)
AttributeError: 'generator' object has no attribute 'id'
虽然生成器函数没有属性“id”,但我能以某种方式解决这个问题吗?这个脚本对于我想要做的事情来说太复杂了吗?!?谢谢,查尔斯