背景
當(dāng)我們使用 CentriMo 進(jìn)行motif 富集后,如采用下面的命令
$ centrimo -oc test test.500l.fa $meme_motif
會(huì)在test
目錄產(chǎn)生三個(gè)文件(centrimo.html
,centrimo.tsv
,site_counts.txt
)型酥,用瀏覽器打開centrimo.html
后昧旨,點(diǎn)擊motif id前面的復(fù)選框后,會(huì)在左邊位置的文本框顯現(xiàn)出motif匹配的序列抽减。
因此允青,問題是我想要獲取每個(gè)motif匹配的序列。一開始卵沉,我想應(yīng)該centrimo.tsv
颠锉,會(huì)有這吧,但是沒找到史汗。然后又去centrimo
的參數(shù)說明里看看有沒相關(guān)參數(shù)設(shè)置琼掠,找到了個(gè),不把匹配序列放進(jìn)html的參數(shù)停撞。瓷蛙。。
既然如此那就只好自己弄了戈毒。
方法
既然能在html上顯示艰猬,那網(wǎng)頁源碼里肯定包含了這些信息。所以查看下網(wǎng)頁源碼:
分析下埋市, 通過
var data
定義個(gè)JavaScript對(duì)象(相當(dāng)于Python中的字典)冠桃,sequences
儲(chǔ)存著所有的序列,motifs下存儲(chǔ)著motif信息恐疲,每個(gè)motif以js對(duì)象表示腊满,其中每個(gè)motif對(duì)象里,seqs
又存儲(chǔ)著序列索引(sequences
數(shù)組的索引培己,沒在圖片中給出碳蛋,可自行查看自己的的網(wǎng)頁源碼)。
因此省咨,我們只要提取出 data 對(duì)象中的sequences
和motifs
數(shù)據(jù), 根據(jù)motifs
下的每個(gè)motif儲(chǔ)存的 seqs索引在sequences
中取出對(duì)應(yīng)的序列就可以獲得了肃弟。
所以上代碼(Python):
import re
import json
from bs4 import BeautifulSoup ## 安裝 pip install beautifulsoup4
file = "centrimo.html"
## 讀取html文件
with open(file, "r") as f:
html = f.read()
## 通過bs4 進(jìn)行解析
soup = BeautifulSoup(html)
# 在script標(biāo)簽下,找到包含 var data的文本零蓉, \s*是用于匹配空格的
script = soup.find('script', text=re.compile('var\s*data\s*=\s*'))
## 通過正則匹配到 var data = {...}; 中data對(duì)象里的數(shù)據(jù)
json_text = re.search('var\s*data\s*=\s*({.*?})\s*;$', script.string, flags=re.DOTALL | re.MULTILINE).group(1)
data = json.loads(json_text) #加載成字典
print(data.keys())
運(yùn)行后笤受,輸出是這樣,代表data數(shù)據(jù)提取成功
dict_keys(['version', 'revision', 'release', 'program', 'cmd', 'options', 'seqlen', 'tested', 'alphabet', 'background', 'sequence_db', 'motif_dbs', 'sequences', 'motifs'])
簡(jiǎn)單的代碼就提取了敌蜂。
sequences = data["sequences"]
motifs = data["motifs"]
extracted_seq = [] # 這里作為一個(gè)例子箩兽,把它們保存在列表里。
for motif in motifs:
seqs_idx = motif["seqs"]
seqs_id = [sequences[i] for i in seqs_idx]
extracted_seq.append({"id": motif["id"], "seq": seqs_id})
print(extracted_seq[1]["seq"][:10])
# ['chr2:22587565-22588065', 'chrX:143482808-143483308', 'chr1:7397843-7398343', 'chr5:88764784-88765284', 'chr9:20651695-20652195', 'chr8:25016942-25017442', 'chr6:21949731-21950231', 'chr10:30842681-30843181', 'chr3:138442803-138443303', 'chr2:3283792-3284292']
之后做什么處理章喉,就看各自的需求了汗贫。
在此身坐,結(jié)束了。
參考
https://stackoverflow.com/questions/13323976/how-to-extract-a-json-object-that-was-defined-in-a-html-page-javascript-block-us
https://meme-suite.org/meme/doc/centrimo.html?man_type=web