超簡(jiǎn)單python腳本實(shí)現(xiàn)從resfinder+blast下機(jī)數(shù)據(jù)到csv抗性基因矩陣

今天還是在做張阿姨的項(xiàng)目,還是那100多個(gè)菌,她說要blast一下抗性基因,那就比咯,最出名與權(quán)威的的細(xì)菌抗性基因庫自然肯定是resfinder了。

for i in $(cat list); do echo i; mkdir ${i}_re; python resfinder.py -i ${i}_new.fa -o ${i}_re -p resfinder  -t 0.95 -l 0.90 > ${i}_out; done

寫個(gè)循環(huán),刷刷弄完真開心。

問題來了!


圖片.png

生成的json結(jié)果的命名全是一樣的!都是data_resfinder.json
只有生成的目錄文件名不一樣,噢不。怎么辦。


圖片.png

機(jī)智的我們來看看resfinder的py腳本。噢一千多行,放棄!好吧其實(shí)我還是找到了他的輸出指令。想想算了我要做矩陣它json我還是要處理的。一步到位吧,直接用我們">"出來的result文件處理好了!
應(yīng)該是輸出文件指令吧。。。

我們來看看輸出的result是什么樣子的:


圖片.png

前面一千多行的廢話。要的只是這幾個(gè)字符
圖片.png

那就easy了!
#resfinder轉(zhuǎn)csv
import os 
from collections import OrderedDict
import csv

forall = OrderedDict()

yourdir = "C:/Users/Administrator/Desktop/output/"#input("dir:")#輸入文件夾名字
mylist = os.listdir(yourdir)#批量讀取文件名

首先先讀讀包,引入一下文件。
然后創(chuàng)建一個(gè)篩選器。

#提取函數(shù)
def select(file):
    for c in file.readlines():
        #c = c.strip()
        if len(c) > 70:
            if c.find("No hit found")  == -1:
                if c.find("run_info")  == -1:
                    if c[70] != " ":
                        c = c.strip()
                        c = c.replace("{","")
                        c = c.replace("'","")
                        c = c.replace('"',"")
                        temp = c.find("HSP_length")
                        c = c[:temp-2]
                        c = c.split()
                        last = c[-1]
                        forall[i].append(last)

再要一個(gè)判斷器判斷該耐藥基因在該個(gè)體中是否存在,超簡(jiǎn)單!

#判斷存在函數(shù)
def exist():
    for k in forall[i]:
        if j == k:
            temp = 1
            break
        else:temp = 0
    return temp

最后主程序以及寫到csv中。

for i in mylist:
    file=open(yourdir+i,'r')
    forall[i] =[]
    select(file)
    #print(forall)
    file.close()

forall_name = []
for i in forall.keys():

    forall_name.append(i)
outgo = forall[forall_name[0]]
for j in range(len(forall_name)):
    outgo = list(set(outgo).union(forall[forall_name[j]]))
    #print(outgo)

outmat = OrderedDict()
data = []
for i in forall.keys():
    outmat[i] = []
    for j in outgo:
        ex = exist()
        outmat[i].append(ex)
    outmat[i].append(i)
    data.append(outmat[i])
   
     ##print(data)
with open('test.csv', 'w', newline='') as t_file:
    csv_writer = csv.writer(t_file)
    csv_writer.writerow(outgo)
    for l in data:
       csv_writer.writerow(l)
    

生成矩陣用EXCEL打開如下嘿嘿嘿,又可以畫圖了嘿嘿嘿。

圖片.png

好吧原本剛開始是想引入json進(jìn)行處理的,但后來發(fā)現(xiàn)好像又不是標(biāo)準(zhǔn)的json格式,咱手動(dòng)搞吧,看需求嘛。
圖片.png

畢竟我大杰尼龜都說好。
resfinder教程(http://www.itdecent.cn/p/136e56b16a5a

最后編輯于
?著作權(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ù)。

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