我有以下的txt檔案(只給了一個片段)
chr1_964906_A/G chr1:964906 G ENSG00000187961 ENST00000622660 Transcript intron_variant - - - - IMPACT=MODIFIER;STRAND= 1
chr1_964939_G/A chr1:964939 A ENSG00000187961 ENST00000338591 轉錄內含子變體 - - - - IMPACT=MODIFIER;STRAND=1
chr1_964939_G/A chr1:964939 A ENSG00000187583 ENST00000379407 轉錄本上游_基因變體 - - - - IMPACT=MODIFIER;DISTANCE=1563;STRAND= 1
chr1_964939_G/A chr1:964939 A ENSG00000187583 ENST00000379409 Transcript upstream_gene_variant - - - - -。
有許多未知的各種ENSG數字,如ENSG00000187583等。每個ENSG字串的整數計數為11。
我必須計算每個基因(ENSGxxx)包含多少個內含子_變數和上游基因_變數。 并將其輸出到csv檔案。
我使用字典來實作這一目的。我試著寫這段代碼,但不確定語法是否正確。 邏輯應該是:如果這11個數字不在字典中,就應該加上1的值。如果它們已經在字典中,值應該改為x 1。我目前有這樣的代碼,但我不是真正的Python程式員,不確定語法是否正確。
with open(file, 'rt') as f。
data = f.readlines()
Count = 0: data = f.readlines()
d = {}
for line in data:
if line[0] == "#"/span>:
output.write(line)
if line.__contains__('ENSG'):
d[line.split('ENSG')[1][0:11]] =1
if 1 in d。
d=1
else:
Count = 1 else: Count = 1
有什么建議嗎?
謝謝你!
uj5u.com熱心網友回復:
你可以試試這個:
from collections import Counter
with open('data.txt') as fp。
ensg = []
for line in fp:
idx = line.find('ENSG')
if not line.startswith('#') and idx != -1:
ensg.append(line[idx 4:idx 15] )
count = Counter(ensg)
>>> count
Counter({'00000187961': 2, '00000187583': 2})
uj5u.com熱心網友回復:
這里是對你的要求的另一種解釋:-
我修改了你的樣本資料,使第一個ENG值為ENSG00000187971,以強調這個作業原理。D = {}。
with open('eng.txt') as eng。
for line in eng:
if not line.startswith('#'/span>):
t = line.split()
V = t[6]
E = t[3]
if not V in D。
D[V] = {}。
if not E in D[V] 。
D[V][E]=1
else:
print(D)
這個的輸出是:-
{'intron_variant': {'ensg00000187971': 1, 'ensg00000187961': 1}, 'upstream_gene_variant': {'ENSG00000187583': 2}}
因此,你現在擁有的是一個以變體為鍵的字典。每個變體都有自己的字典,由ENSG值和每個ENSG值的出現次數來決定
因此,你現在有一個由變體決定的字典。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332795.html
標籤:
