在python中解析包含multifasta BLAST结果的xml文件

时间:2016-04-15 10:02:16

标签: python xml bioinformatics biopython blast

我试图解析包含multifasta BLAST结果的xml文件 - 这是link - 它的大小约为400kB。程序应返回四个序列名称。每个下一个结果应该在第一个之后(包含最佳对齐)"< Iteration_iter-num> n< Iteration_iter-num />",其中n = 1,2,3,...

像这样:

< Iteration_iter-num >1< /Iteration_iter-num >

****Alignment****
sequence: gi|171864|gb|AAC04946.1| Yal011wp [Saccharomyces cerevisiae]

< Iteration_iter-num >2< /Iteration_iter-num >

****Alignment****
sequence: gi|330443384|ref|NP_009392.2| 

< Iteration_iter-num >3< /Iteration_iter-num >

****Alignment****
sequence: gi|6319310|ref|NP_009393.1|

< Iteration_iter-num >4< /Iteration_iter-num >

****Alignment****
sequence: gi|6319312|ref|NP_009395.1|

但结果我的程序返回:

<Iteration_iter-num>1</Iteration_iter-num>
****Alignment****
sequence: gi|171864|gb|AAC04946.1| Yal011wp [Saccharomyces cerevisiae]

<Iteration_iter-num>2</Iteration_iter-num>
****Alignment****
sequence: gi|171864|gb|AAC04946.1| Yal011wp [Saccharomyces cerevisiae]

<Iteration_iter-num>3</Iteration_iter-num>
****Alignment****
sequence: gi|171864|gb|AAC04946.1| Yal011wp [Saccharomyces cerevisiae]

<Iteration_iter-num>4</Iteration_iter-num>
****Alignment****
sequence: gi|171864|gb|AAC04946.1| Yal011wp [Saccharomyces cerevisiae]

如何从此xml文件获取另一个BLASTA结果?

这是我的代码:

from Bio.Blast import NCBIXML
from bs4 import BeautifulSoup

result = open ("BLAST_left.xml", "r")
records = NCBIXML.parse(result)
item = next(records)

file = open("BLAST_left.xml")
page = file.read()
soup = BeautifulSoup(page, "xml")
num_xml_array = soup.find_all('Iteration_iter-num')
i = 0
for records in records:
    for itemm in num_xml_array:
        print (itemm)
        for alignment in item.alignments:
            for hsp in alignment.hsps:
                print("\n\n****Alignment****")
                print("sequence:", alignment.title)
            break
        itemm = num_xml_array[i+1]
    break

//我知道我的英语并不完美,但我真的不知道该怎么做而且我没有任何人要求它,所以我选择了你:)

2 个答案:

答案 0 :(得分:1)

我认为Biopython是解析XML的更好选择,不需要使用BeautifulSoup:

from Bio.Blast import NCBIXML


result = open("BLAST_left.xml", "r")
records = NCBIXML.parse(result)

for i, record in enumerate(records):
    for align in record.alignments:
        print("Iteration {}".format(i))
        print(align.hit_id)
        break  # Breaking here gives you only the best HSP.

答案 1 :(得分:0)

You can use python in-build module xml.etree.ElementTree to parse the xml

import xml.etree.ElementTree as ET
tree = ET.parse('BLAST_left.xml')
doc = tree.getroot()
for item in doc.find('BlastOutput_iterations'):
    print '< Iteration_iter-num >{0}< /Iteration_iter-num >'.format(item.find('Iteration_iter-num').text)
    print '** ** Alignment ** **'
    print 'sequence:{0}|{1}'.format(item.find('Iteration_hits/Hit/Hit_id').text, item.find('Iteration_hits/Hit/Hit_def').text)