LoginSignup
2
5

More than 5 years have passed since last update.

BiopythonでBLAST結果をファイルに保存せずに解析する [バイオ]

Posted at

biopythonでのblast結果の解析には
NCBIXML.parse(open('blast結果のxmlファイルパス'))
がよく使われると思う。
しかし、blastの結果がファイルでない or ファイルに保存したくないこともしばしば。

こんな時は、
NCBIXML.parse(io.StringIO(blastの結果))
を用いることで、blastの実行結果をファイルに保存せずに解析することができる。

blast_do_not_save_results.py
#!/usr/bin/env python3

import io
from Bio.Blast.Applications import NcbiblastnCommandline
from Bio.Blast import NCBIXML

db_path='path/to/the/blast_db'
fasta_path='path/to/the/query/fasta'

# blastの結果を out に入れる
out=NcbiblastnCommandline(db=db_path, query=fasta_path, evalue=1e-5, outfmt=5)()[0]
# blastの結果をparse
blast_records=NCBIXML.parse(io.StringIO(out))
for blast_record in blast_records:
    for alignment in blast_record.alignments:
        for hsp in alignment.hsps:
            print('****Alignment****')
            print('sequence:', alignment.title)
            print('length:', alignment.length)
            print('e-value:', hsp.expect)
            print(hsp.query[0:75] + '...')
            print(hsp.match[0:75] + '...')
            print(hsp.sbjct[0:75] + '...')

上記のスクリプトは以下と同じ。
ただし、以下はblastの結果をxmlファイルに書き出す。

blast_save_results_as_xml.py
#!/usr/bin/env python3

import io
from Bio.Blast.Applications import NcbiblastnCommandline
from Bio.Blast import NCBIXML

db_path='path/to/the/blast_db'
fasta_path='path/to/the/query/fasta'

# blastの結果を out に入れる
out=NcbiblastnCommandline(db=db_path, query=fasta_path, evalue=1e-5, outfmt=5)()[0]
# blastの結果をxmlファイルに保存
with open('blast_out.xml', 'w') as outfile:
    outfile.write(out)
# 保存したxmlファイルをファイルオブジェクトにする
result_handle=open('blast_out.xml')
# blastの結果をparse
blast_records=NCBIXML.parse(result_handle)
for blast_record in blast_records:
    for alignment in blast_record.alignments:
        for hsp in alignment.hsps:
            print('****Alignment****')
            print('sequence:', alignment.title)
            print('length:', alignment.length)
            print('e-value:', hsp.expect)
            print(hsp.query[0:75] + '...')
            print(hsp.match[0:75] + '...')
            print(hsp.sbjct[0:75] + '...')

ポイント

こちらによると、io.StringIO は「ファイルオブジェクトのように見えるオブジェクト」を作るらしい。
io.StringIO は python3のみで使用可能なので注意。
python2では io.BytesIO を使うことで同じことができる。

環境

Python 3.7.1
biopython 1.72
BLAST 2.8.1+
Ubuntu 18.04

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5