如何在Python中创建包含多个fasta序列和id的列表

时间:2015-04-14 12:33:55

标签: python extract bioinformatics biopython fasta

我是Python新手。我正在尝试将包含8个染色体序列的基因组fasta文件作为输入,针对查询序列进行爆破并提取前50个命中。 Hre是我的代码:

from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Blast import NCBIXML
from Bio.Blast.Applications import NcbiblastnCommandline
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
import os

db = list(SeqIO.parse('genome.fasta', 'fasta'))
for i in range(len(db)):
    print "Chromosome_"+str(i+1)
    print('Doing the BLAST and retrieving the results...')
    output_handle = open("dbn.fasta", "w")
    nseq=db[i]
    SeqIO.write(nseq, output_handle, "fasta")
    output_handle.close()
    os.system("makeblastdb -in dbn.fasta -dbtype nucl -out dbn")
    result_handle= NcbiblastnCommandline(query="sequence.fasta", db = "dbn", outfmt= 5, out="my_blast_"+str(i)+".xml", evalue = 0.00001, task = "megablast")
    stderr, stdout = result_handle()
    E_VALUE_THRESH = 1e-100
    c=0
    print "Extracting hits for Chromosome"+str(i+1)+"in another file"
    for record in NCBIXML.parse(open("my_blast_"+str(i)+".xml")):
        if record.alignments:
            for align in record.alignments:
                for hsp in align.hsps:
                    if hsp.expect < E_VALUE_THRESH:
                        if c>50: break
                        start=hsp.sbjct_start
                        end=hsp.sbjct_end
                        newSeq = db[i].seq[:end]
                        newSeq = newSeq[start:]
                        ids=db[i].id+str(c)
                        myseq[c]=SeqRecord(Seq(newSeq,IUPAC.DNA))
                        myseq[c].id=str(ids)                        
                        c=c+1

    output_handler = open("example_"+str(i)+".fasta", "w")
    SeqIO.write(myseq, output_handler, "fasta")
    output_handler.close()

它在第33行给出了一个错误:

AttributeError: 'module' object has no attribute 'DNA'

我试图删除IUPAC.DNA,制作一行:

myseq[c]=SeqRecord(Seq(newSeq)

它给我一个类型错误:

TypeError: The sequence data given to a Seq object should be a string (not another Seq object etc)

有没有办法解决这个问题,有没有其他方法可以创建一个多快速列表变量?

2 个答案:

答案 0 :(得分:0)

也许你必须出于某种原因解析python中的fasta,但如果没有,为什么不直接保留文件并从命令行调用blast?然后解析python中的结果。

import subprocess

subprocess.call('makeblastdb -dbtype nucl -in dbn.fasta -out dbn.DATABASE')
subprocess.call('blastn -db dbn.DATABASE -query genome.fasta -outfmt 7 -out blast_results')

for line in open('blast_results') # outfmt 7 is tabular output
    if not line.startswith('#'):
        # Get top 50 hits (per chromosome I assume)

答案 1 :(得分:0)

感谢大家的建议。我能够从染色体中提取序列,并将它们直接写入另一个文件,以&#39;&gt;&#39;

开头
ids=db[i]+"_"+str(hsp.sbjct_start)+"_"+str(hsp.sbjct_end)
f.write(">"+str(ids) + "\n")
f.write(str(newSeq) + "\n")