我正在尝试将成百上千个.fasta文件连接成一个包含所有序列的大型fasta文件。我还没有在论坛中找到一个具体的方法来实现这一点。我确实遇到了来自http://zientzilaria.heroku.com/blog/2007/10/29/merging-single-or-multiple-sequence-fasta-files的这段代码,我对它进行了一些调整。
Fasta.py包含以下代码:
class fasta:
def __init__(self, name, sequence):
self.name = name
self.sequence = sequence
def read_fasta(file):
items = []
index = 0
for line in file:
if line.startswith(">"):
if index >= 1:
items.append(aninstance)
index+=1
name = line[:-1]
seq = ''
aninstance = fasta(name, seq)
else:
seq += line[:-1]
aninstance = fasta(name, seq)
items.append(aninstance)
return items下面是用于连接.fasta文件的改编脚本:
import sys
import glob
import fasta
#obtain directory containing single fasta files for query
filepattern = input('Filename pattern to match: ')
#obtain output directory
outfile = input('Filename of output file: ')
#create new output file
output = open(outfile, 'w')
#initialize lists
names = []
seqs = []
#glob.glob returns a list of files that match the pattern
for file in glob.glob(filepattern):
print ("file: " + file)
#we read the contents and an instance of the class is returned
contents = fasta.read_fasta(open(file).readlines())
#a file can contain more than one sequence so we read them in a loop
for item in contents:
names.append(item.name)
seqs.append(item.sequence)
#we print the output
for i in range(len(names)):
output.write(names[i] + '\n' + seqs[i] + '\n\n')
output.close()
print("done")它能够读取fasta文件,但新创建的输出文件不包含序列。我收到的错误是由于fasta.py引起的,这超出了我的能力范围:
Traceback (most recent call last):
File "C:\Python32\myfiles\test\3\Fasta_Concatenate.py", line 28, in <module>
contents = fasta.read_fasta(open(file).readlines())
File "C:\Python32\lib\fasta.py", line 18, in read_fasta
seq += line[:-1]
UnboundLocalError: local variable 'seq' referenced before assignment有什么建议吗?谢谢!
发布于 2012-08-01 06:59:08
我认为使用python来完成这项工作有点过头了。在命令行上,使用.fasta或.fa扩展名连接单个/多个fasta文件的快速方法是:
cat *.fa* > newfile.txt发布于 2012-07-31 01:23:52
问题出在fasta.py
else:
seq += line[:-1]
aninstance = fasta(name, seq)在read_fasta(file)开始之前尝试初始化seq。
编辑:更多说明
当您第一次调用read_fasta时,文件中的第一行不是以>开头的,因此您将第一行附加到尚未初始化(甚至没有声明)的字符串seq中:您将一个字符串(第一行)附加到一个空值。堆栈中存在的错误解释了问题:
UnboundLocalError: local variable 'seq' referenced before assignment发布于 2012-09-30 00:48:17
不是python程序员,但问题代码似乎试图将每个序列的数据压缩到一行中,并用空行分隔序列。
>seq1
00000000
11111111
>seq2
22222222
33333333会变成
>seq1
0000000011111111
>seq2
2222222233333333如果确实需要这样做,那么上面基于cat的解决方案将无法工作。除此之外,cat是最简单、最有效的解决方案。
https://stackoverflow.com/questions/11726340
复制相似问题