Python和Perl處理fasta文件對(duì)比_2018-09-11

從fasta中抽取需要的序列:
Python方法一:(這種方式最慢)
由于平時(shí)工作比較忙,工作中遇到的問題都沒有及時(shí)記錄,現(xiàn)在有空時(shí)間了所以整理一下一些常見的問題及技巧供大家參考:

!/usr/bin/python

import sys
def Fasta(inputfile) :
f = open(inputfile,"r")
fastadic = {}
while True :
line = f.readline().rstrip()
if len(line) == 0 :
break
else :
pass
if line.startswith(">") :
name = line.split()[0]
fastadic[name] = ""
else :
fastadic[name]+=line
f.close()
return fastadic

def usage():
print ("1,fasta\n2,list")

if len(sys.argv) != 3 :
usage()
sys.exit()

print (sys.argv[0])

fastafile = sys.argv[1]
listfile = sys.argv[2]

dic = Fasta(fastafile)
ff=open(listfile,"r")
while 1:
line1 = ff.readline().rstrip()
if len(line1) == 0 :
break
else :
pass
array = line1.split("\t")
if ">"+array[0] in dic.keys() :
print (">"+array[0]+"\n"+dic[">"+array[0]])
else :
print ("Error:"+line1)
ff.close()
Python方法二:(次慢)

!/usr/bin/python

import sys
def Fasta(inputfile) :
f = open(inputfile,"r")
fastadic = {}
while True :
line = f.readline().rstrip()
if len(line) == 0 :
break
else :
pass
if line.startswith(">") :
name = line.split()[0]
fastadic[name] = []
else :
fastadic[name].append(line)
f.close()
return fastadic

def usage():
print ("1,fasta\n2,list")

if len(sys.argv) != 3 :
usage()
sys.exit()

print (sys.argv[0])

fastafile = sys.argv[1]
listfile = sys.argv[2]

dic = Fasta(fastafile)
ff=open(listfile,"r")
while 1:
line1 = ff.readline().rstrip()
if len(line1) == 0 :
break
else :
pass
array = line1.split("\t")
if ">"+array[0] in dic.keys() :
print (">"+array[0]+"\n"+"".join(dic[">"+array[0]]))
else :
print ("Error:"+line1)
ff.close()
Perl 方法三(最快)

!/usr/bin/perl -w

die "perl 0 <inputfastafile> <list> \n" if @ARGV != 2 ; use strict; use warnings; my %fasta ; my @name; open I,ARGV[0] ;
while (<I>) {
chomp;
if (/^>/) {
@name = split/\s+/,_;fasta{name[0]} = "" ; } else {fasta{name[0]}.=_ ;
}
}
close I;

open T,ARGV[1] ; while (<T>) { chomp; my @tax = split/\t/ ,_ ;
if (exists fasta{">".tax[0]}) {
print ">".tax[0],"\n",fasta{">".$tax[0]}, "\n" ;
}
}

close T;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容