将大fasta拆分成多个文件,不能用GI号命名
Posted
技术标签:
【中文标题】将大fasta拆分成多个文件,不能用GI号命名【英文标题】:Split large fasta into mulitple files, can't name them with GI number 【发布时间】:2012-05-30 15:46:33 【问题描述】:首先我应该说我对 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”,但我能以某种方式解决这个问题吗?这个脚本对于我想要做的事情来说太复杂了吗?!?谢谢,查尔斯
【问题讨论】:
【参考方案1】:因为您一次只需要一条记录,您可以放弃 batch_iterator 包装器和枚举:
for seq_record in record_iter:
然后你想要的是每条记录的 id 属性,而不是整个迭代器:
for seq_record in record_iter:
outfile = "c:\python32\myfiles\0.fasta".format(seq_record.id)
handle = open(outfile, "w")
count = SeqIO.write(seq_record, handle, "fasta")
handle.close()
供您参考,生成器错误是您尝试从对象record_iter
获取属性id
的结果。 record_iter
不是一条记录,而是一组记录,它们被保存为 Python 生成器,有点像一个正在处理的列表,因此您不必读取整个文件一次,内存使用效率更高。更多关于生成器:What can you use Python generator functions for?,http://docs.python.org/tutorial/classes.html#generators,
【讨论】:
似乎是最好和最简单的方法。使用with open(outfile, "w") as handle:
打开输出文件会更干净
或者不要在代码中打开,而是让 Biopython 来做:count = SeqIO.write(seq_record, outfile, "fasta")以上是关于将大fasta拆分成多个文件,不能用GI号命名的主要内容,如果未能解决你的问题,请参考以下文章