1. 解決的實(shí)際問題,計(jì)算人類參考基因組hg38每條染色體堿基數(shù)據(jù)ATCG的比例
2. 計(jì)算人類參考基因組hg38的外顯子區(qū)域堿基數(shù)量
3. 目的是了解基礎(chǔ)python語法
4. 參考書目:python編程從入門到實(shí)踐,參考視頻資料見最底部
5. 測試數(shù)據(jù)下載地址鏈接:https://share.weiyun.com/5Xmmzdz 密碼:6q2y5j
打開python3
vim 1.txt
:wq ##Esc+ :wq保存退出
python3 # 打開python3
f = open('./1.txt','r')
for i in f:
print (i)
with open('./1.txt') as file_object:
for line in file_object:
print (line)
圖1
f = open('./2.txt','w')
with open('./1.txt','r') as imput_f:
for line in imput_f:
line = line.strip()
result= int(line)+int(line)
f.write(str(result)+'\n')
f.close()
圖2
output_file = open('./2.txt','a') ## 附加內(nèi)容
with open('./1.txt','r') as imput_f:
for line in imput_f:
line = line.strip()
result= int(line)+int(line)
output_file.write(str(result)+'\n')
output_file.close()
圖3
完成探索人類基因組GC含量與gene密度的關(guān)系;
提示:
1.將染色體成分1Mb大小的bin統(tǒng)計(jì)GC含量;
2.將染色體分為1Mb大小的bin統(tǒng)計(jì)gene的密度髓迎;
3.使用R將這兩者用散點(diǎn)圖進(jìn)行繪圖;
4.使用R的線性回歸函數(shù)lm()進(jìn)行回歸;
5.R回歸部分狮杨,參考資料
blog.fens.me/r-linear-regression/
def my_abs(imput):
if imput >= 0:
return imput
else:
return -imput
my_abs(-10)
作業(yè)
人類的線粒體長度大約為16.7Kb,請讀取人類線粒體參考基因組序列信息(fasta格式)到忽,統(tǒng)計(jì)各種堿基的數(shù)量以及人類線粒體參考基因組的總長度橄教。
編程作業(yè)
# _*_ coding:UTF-8 _*_
### 保證中文不報(bào)錯(cuò)pycharm
選取參考基因組hg38作為測試數(shù)據(jù)1000-1300行 n 和 p是同時(shí)出現(xiàn)的
cat ~/reference/UCSC/hg38/hg38.fa| sed -n '1000,1300p' >> ~/project/python/t.txt
cd - # 回到上一個(gè)目錄
python3
圖4
chrM_genome = ''
with open('./t.txt','r') as imput_f:
for line in imput_f:
line = line.strip().upper() ## 去除前后空格,大寫
chrM_genome = chrM_genome + line
print (len(chrM_genome))
print (chrM_genome.count('A'))
print ('the char A count is : {0}'.format(chrM_genome.count('A'))) # format 將其格式化
Fastq 格式 四行
圖5
>>> with open(r'./fa_q.txt','r') as imput:
... for index,line in enumerate(imput):
... if index % 4==0:
... print ('>'+line.strip()[1:])
... elif index % 4 ==1:
... print (line.strip())
... elif index % 4==2:
... continue
... elif index %4==3:
... continue
...
>SRR1039512.325 HWI-ST177:314:C12K6ACXX:1:1101:5657:2438 length=63
TCAGAAGAAAAGCATATGTCTGCCATGGGACTATTGCAGTGCGTCTCCATCAGTGTTAACACA
>SRR1039512.326 HWI-ST177:314:C12K6ACXX:1:1101:5550:2446 length=63
TAAGCAGTGCTTGAATTATTTGGTTTCGGTTGTTTTCTATTAGACTATGGTGAGCTCAGGTGA
>SRR1039512.327 HWI-ST177:314:C12K6ACXX:1:1101:5908:2367 length=63
TGGGGAATAGCTTCTCAAGGGCAAGTGCTGTTTCCATACTAGTTCTTTTCCTTGCTCTCTTAT
>SRR1039512.328 HWI-ST177:314:C12K6ACXX:1:1101:5852:2396 length=63
GGAGGAAGCCCACGGTGGGATCTGGCACAAAGATGTAGAGCCGTTTCCGCTCATCGGTCTCCA
>SRR1039512.329 HWI-ST177:314:C12K6ACXX:1:1101:5768:2409 length=63
ACCTGGCAGTGCTGCAACAGTATCTGCCTCTACAAGTAACATCATACCCCCAAGACACCAGAA
>SRR1039512.330 HWI-ST177:314:C12K6ACXX:1:1101:5840:2413 length=63
GCAGAGGTAATTGCCTGAATCCTTCTGTTGTAGACTACGTAGCAGAAGGCCTTGATCTGTCCT
>SRR1039512.331 HWI-ST177:314:C12K6ACXX:1:1101:5826:2463 length=63
GAAAGGCAAGGAGGAAGCTTATCTATGAAAAAGCAAAGCACTATCACAAGGAATATAGGC
>SRR1039512.332 HWI-ST177:314:C12K6ACXX:1:1101:5888:2477 length=63
GTCTGTCTCTTGCTTCAACAGTGTTTGGACGGAACAGATCCGGGGACTCTCTTCCAGCCTCCG
>SRR1039512.333 HWI-ST177:314:C12K6ACXX:1:1101:6208:2288 length=63
GTCATAACCACCACCGCTTACACCTGGAGGTCCAGGAGGGCCAGGGGGACCAGGGGGGCCAGC
##每隔40一行
with open(r'C:\Users\kexin\Desktop\python\fa_q.txt','r') as imput:
for index,line in enumerate(imput):
if index % 4==0:
print ('>'+line.strip()[1:])
elif index % 4 ==1:
for i in range(0,len(line.strip()),40):
print (line.strip()[i:i+40])
elif index % 4==2:
continue
elif index %4==3:
continue
output_file = open (r'C:\Users\kexin\Desktop\python\result2.fastq','w')
with open(r'C:\Users\kexin\Desktop\python\fa_q.txt','r') as imput:
for index,line in enumerate(imput):
if index % 4==0:
output_file.write(('>'+line.strip()[1:])+'\n')
elif index % 4 ==1:
for i in range(0,len(line.strip()),40):
output_file.write(line.strip()[i:i+40]+'\n')
elif index % 4==2:
print (index)
elif index %4==3:
continue
output_file.close()
讀取fasta文件
with open (r'C:\Users\kexin\Desktop\python\result2.fastq','r') as input_file:
seq=''
header= input_file.readline().strip()[1:] ## 讀取第一行
for line in input_file:
if line[0]!='>':
seq =seq.strip()+line ### 這里是要確保剛剛被40個(gè)一行分隔的seq數(shù)據(jù)重新疊加
elif line[0]=='>':
print (header)
print (seq)
header = line.strip()[1:]
seq = '' ### 一個(gè)循環(huán)結(jié)束將seq清空
print (header)
print (seq)
一個(gè)能讀取fasta格式的函數(shù)(收藏版)
def read_fasta(file_path=''):
line = ''
try:
fasta_handle=open(file_path,'r')
except:
raise IOError('you input FAST file is not right')
while True:
line = fasta_handle.readline()
if line == '':
return
if line[0] =='>':
break
## while the file is not empty, load FASTA file
while True:
if line[0] !='>':
raise ValueError("Records in Fasta files should start with '>'")
title = line[1:].rstrip()
lines =[]
line = fasta_handle.readline()
while True:
if not line:
break
if line[0] == '>':
break
lines.append(line.rstrip())
line = fasta_handle.readline()
yield title, ''.join(lines).replace('','').replace('\r','')
if not line:
return
fasta_handle.close()
assert False, 'your input fasta file have format problem'
read_fasta(file_path=r'C:\Users\kexin\Desktop\python\result2.fastq') ## 出現(xiàn)一個(gè)報(bào)錯(cuò)喘漏,在windows里面护蝶,要加上r,不然\代表轉(zhuǎn)義:參考https://blog.csdn.net/caibaoH/article/details/78335094
for header,seq in read_fasta(file_path=r'C:\Users\kexin\Desktop\python\result2.fastq'):
print (header)
print (seq)
計(jì)算人類參考基因組的序列長度
分析步驟:
利用讀取fasta的代碼讀取基因組序列信息
統(tǒng)計(jì)每條序列的長度翩迈,并輸出
統(tǒng)計(jì)人類參考基因組的總長度持灰,并輸出
統(tǒng)計(jì)每條染色體N的長度,并輸出
提取基因組特定區(qū)域的序列负饲,并輸出(支持+/-鏈)
hg38_genome={}
for chr_name, chr_seq in read_fasta(file_path=r'/four/yqchen/reference/UCSC/hg38/hg38.fa'):
hg38_genome[chr_name]=chr_seq
這里要用絕對路徑不然報(bào)錯(cuò)
圖6
hg38_genome.keys()
for chr_name in hg38_genome.keys():
print (chr_name,len(hg38_genome.get(chr_name)))
## 這里有點(diǎn)不對堤魁,但是無所謂了
圖7
hg38_total_len=0
for index in range (1,26):
if index<= 22:
chr_name = 'chr{0}'.format(index)
elif index == 23:
chr_name = 'chrX'
elif index == 24:
chr_name = 'chrY'
elif index == 25:
chr_name = 'chrM'
print (chr_name,len(hg38_genome.get(chr_name)))
這里結(jié)果是正確的,這是為什么返十?這里沒搞明白的妥泉。
圖8
hg38_total_len = 0
for index in range (1,26):
if index<= 22:
chr_name = 'chr{0}'.format(index)
elif index == 23:
chr_name = 'chrX'
elif index == 24:
chr_name = 'chrY'
elif index == 25:
chr_name = 'chrM'
hg38_total_len= hg38_total_len + int(len(hg38_genome.get(chr_name)))
print (hg38_total_len) ### 和上面那一句分開執(zhí)行
圖9
圖10
len(hg38_genome['chr21'])
hg38_genome['chr21'].count('N')
hg38_genome['chr22'].count('N')
## 正負(fù)鏈
chr_name='chr1'
chr_start=10000
chr_end=10300
hg38_genome[chr_name][chr_start-1:chr_end-1].upper()
#### 反向互補(bǔ)
import string
translate_table=string.maketrans('ATGC','TACG')
a=hg38_genome[chr_name][chr_start-1:chr_end-1].upper()
a.translate(translate_table)[::-1]
##方向互補(bǔ)定義函數(shù)
import string
def com_rev(input):
translate_table=string.maketrans('ATGC','TACG')
return input.upper().translate(translate_table)[::-1]
編碼基因長度,從參考基因組注釋信息找
with open(r'C:/Users/kexin/Desktop/python/hg38_RefSeq_genetable') as input_f:
header = input_f.readline()
for line in input_f:
line=line.strip().split('\t')
print (line)
break
with open(r'C:/Users/kexin/Desktop/python/hg38_RefSeq_genetable') as input_f:
header = input_f.readline() #### 讀一行 不要用readlines
for line in input_f:
line=line.strip().split('\t')
exon_count = int(line [8])
exon_start =line[9].strip(',') ### 去掉最后的逗號
print (exon_start)
break
with open(r'C:/Users/kexin/Desktop/python/hg38_RefSeq_genetable') as input_f:
header = input_f.readline() #### 讀一行 不要用readlines
for line in input_f:
line=line.strip().split('\t')
# print (line)
exon_count = int(line [8])
exon_start =line[9].strip(',')
exon_end =line[10].strip(',')### 去掉最后的逗號
print (exon_start)
print (exon_end)
break
with open(r'C:/Users/kexin/Desktop/python/hg38_RefSeq_genetable') as input_f:
header = input_f.readline() #### 讀一行 不要用readlines
for line in input_f:
line=line.strip().split('\t')
# print (line)
exon_count = int(line [8])
exon_start = line[9].strip(',').split(',') ### map函數(shù)int用于后面的列表
exon_end = line[10].strip(',').split(',')
print (exon_start)
print (exon_end)
break
with open(r'C:/Users/kexin/Desktop/python/hg38_RefSeq_genetable') as input_f:
header = input_f.readline() #### 讀一行 不要用readlines
for line in input_f:
line=line.strip().split('\t')
# print (line)
exon_count = int(line [8])
exon_start = map(int,line[9].strip(',').split(',')) ### map函數(shù)int用于后面的列表
exon_end = map(int,line[10].strip(',').split(','))
print (exon_start)
print (exon_end)
break
with open(r'C:/Users/kexin/Desktop/python/hg38_RefSeq_genetable') as input_f:
header = input_f.readline() #### 讀一行 不要用readlines
for line in input_f:
line=line.strip().split('\t')
# print (line)
exon_total_len=0
exon_count = int(line [8])
exon_start = map(int,line[9].strip(',').split(',')) ### map函數(shù)int用于后面的列表
exon_end = map(int,line[10].strip(',').split(','))
for index in range(exon_count):
exon_total_len= exon_total_len+exon_end[index]-exon_start[index]
print (exon_total_len)
print (exon_start)
print (exon_end)
break
這里python3 會(huì)報(bào)錯(cuò)
1555423217495.png
解決方案洞坑,在map基礎(chǔ)上加上list
1555423298540.png
with open(r'C:/Users/kexin/Desktop/python/hg38_RefSeq_genetable') as input_f:
header = input_f.readline() #### 讀一行 不要用readlines
for line in input_f:
line=line.strip().split('\t')
# print (line)
exon_total_len=0
exon_count = int(line [8])
exon_start = list(map(int, line[9].strip(',').split(','))) ### map函數(shù)int用于后面的列表
exon_end = list(map(int, line[10].strip(',').split(',')))
for index in range(exon_count):
exon_total_len= exon_total_len+exon_end[index]-exon_start[index]
print (exon_total_len)
print (exon_start)
print (exon_end)
break
完整計(jì)算版:
gene_exon_len_dict={}
with open(r'C:/Users/kexin/Desktop/python/hg38_RefSeq_genetable') as input_f:
header = input_f.readline() #### 讀一行 不要用readlines
for line in input_f:
line=line.strip().split('\t')
# print (line)
exon_total_len=0
exon_count = int(line [8])
exon_start = list(map(int, line[9].strip(',').split(','))) ### map函數(shù)int用于后面的列表
exon_end = list(map(int, line[10].strip(',').split(',')))
for index in range(exon_count):
exon_total_len= exon_total_len+exon_end[index]-exon_start[index]
gene_id = line[12]
if gene_exon_len_dict.get(gene_id) is None: #如果gene_exon_len_dict字典里沒有這個(gè)基因盲链,加入這個(gè)基因的長度
gene_exon_len_dict[gene_id] = exon_total_len
else:
if gene_exon_len_dict.get(gene_id) < exon_total_len:
gene_exon_len_dict[gene_id] = exon_total_len
len(gene_exon_len_dict)
exon_total =0
for gene_id in gene_exon_len_dict.keys():
exon_total = exon_total+gene_exon_len_dict[gene_id]
# exon_total = exon_total+gene_exon_len_dict.values(gene_id) 這是錯(cuò)誤寫法
print (exon_total)
exon_rate = 111336157 / 3088286401 *100
exon_rate
推薦視頻
https://www.bilibili.com/video/av16064125?from=search&seid=5895915127692784448
https://www.bilibili.com/video/av15887563?from=search&seid=5895915127692784448