Advertisement

生物信息学习笔记整理

阅读量:

做了不少练习,整理一下以前的经验。
主要是归纳一些模块化的东西,提取一些常用的函数还有一些小tricky

复制代码
    # split的用法
    str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
    print (str.split( ))
    print (str.split(' ', 1)) # 从头开始切一刀
    list1 = [ [1,5,7], [10,3, 4], [6, 8, 5]]
    
    # continue的用法
    for list1_item in list1:
    for item in list1_item:
        print(item)
        if(item >= 10):
            print('10以上')
            break
    else:  
        continue
    break
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

对字典排序

复制代码
    # 方法1  据说这种方法更快 
    from operator import itemgetter
    d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}
    sorted(d.items(), key=itemgetter(1), reverse=True)
    # 方法2
    paixu = sorted(d.items(), key=lambda x: x[1],reverse = True)
    
      
      
      
      
      
      
    
复制代码
    # zip()可以把两个列表合成一个字典,顺序不变
    #dictionary = dict(zip(index, cg_percentage))
    
      
      
    
复制代码
    格式化输出
    percent3 = ('%.3f') % percent3
    
      
      
    

enumerate(lines)

复制代码
    # enumerate返回的是一个字典
    # 列表的行数(从0开始)和对应的内容
    line = 列表
    for index,item in enumerate(lines):
    
    
      
      
      
      
      
    

正则

复制代码
    #正则替换字符串的方法
    ①
    re.sub("\([A-Z][a-z].*?\)","",line)
    ②
    regex = re.compile(r'\([A-Z][a-z].*\)')
    for i in lines:
    d = regex.sub("",i)  #把空格替换过去,相当于删除了
    
    # 正则提取文件的方法 group()   
    regex = re.compile(r'\([A-Z][a-z].*\)')
    reg = open("c:/2-1.txt","w") 
    for i in lines:
    m = regex.search(i)
    if m:
        reg.writelines(m.group(0).strip("\(""\)")+"\n")
    
    # 正则search的用法        
    if re.search('ORGANISM',line):
    n=line.split('ORGANISM')[1].strip() # strip()不光可以删除空格 也可以用来删除特定字符串
    print ('> %s : %s' % (n,m))
    
    # 正则分割 re.split()
    import re
    a='Beautiful, is; better*than\nugly'
    # 四个分隔符为:,  ;  *  \n
    x= re.split(',|; |\*|\n',a)
    print((x))
    
    # 正则查找 re.search()
    str = 'user<user@test.com>'
    print (re.search('<(.+)>', str).group(1))
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

按行读文件的方法

复制代码
    while True:
    line = fobj.readline()#按行读取
    if len(line)== 0:
        break #如果遇到文件末尾(前提是文件中间没有空行),跳出循环
    
      
      
      
      
    

逐行读取fastq文件的方法

复制代码
    # 按行读的时候加上计数器,(只读奇数行)
    with open("c:/Test1.fastq","r") as f:
    line_number = 0
    while True:       
        line = f.readline()
        line_number += 1        
        if line_number % 4 == 2 :             
            for i in range(len(line)):
                if line[i] == "C"  or line[i] == "G" :
                    number[i] = 1 + number[i] 
    
      
      
      
      
      
      
      
      
      
      
    

一次读取fasta文件,返回一个大字典

复制代码
    import os
    os.chdir("c:/")
    def readfasta(filename):
    fa = open(filename, 'r')
    res = {}
    ID = ''
    for line in fa:
        #print(line)
        if line.startswith('>'):           
            ID = line#.strip('\n')
            res[ID] = ''
        else:           
            res[ID] += line#.strip('\n')
    return res
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

R语言画饼图,没用ggplot

复制代码
    data <- read.table("c:\ 1-2.txt")
    jpeg("c:\ Users\ mega\ 17.7考核\ pie.jpeg",width=2000,height=2000,res=300)
    pct <- round(val/sum(val)*100)  # 数值用百分比表示
    lbls2 <- paste(key, "  ", pct,"%",sep = "") #加上百分号
    pie(val,labels = lbls2,main = "Pie Chart of Qual")#,col = rainbow(length(lbls2))) 可以改成彩虹色
    dev.off()
    
      
      
      
      
      
      
      
    

R 语言画折线图

复制代码
    # 不用ggplot会很丑
    setwd("c:\ Users\ Desktop") 
    data <- read.table("cg.txt",header = T) 
    plot(data$location,data$frequency,main="折线图",xlab="number",ylab="len",col="red",cex=1,lwd=1,type='o')
    
    用了ggplot:
    # 每条reads的CG分布 画图
    library(ggplot2)
    setwd("c:\ Users\ Desktop") 
    dataa <- read.table("cg.txt",header = T) 
    jpeg("line.jpeg",width=2000,height=2000,res=300) 
    ggplot(dataa, aes(x = location, y = frequency)) + 
    geom_line()+  # 这一句是画出折线的! 
    theme(axis.text.y= element_text(size=10, color="black", face= "bold", vjust=0.5, hjust=0.5))+
    theme(axis.text.x= element_text(size=10, color="black", face= "bold", vjust=0.5, hjust=0.5))+
    theme(axis.title= element_text(size=12, color="black", face= "bold", vjust=0.5, hjust=0.5))+
    ylim(0,1)+  #y轴的范围
    ggtitle("CG location") +  #标题
    theme(plot.title = element_text(hjust = 0.5))+  # 标题的位置
    xlab("Location") + ylab("frequency")  # xy轴的名字,可以覆盖之前的名字
    dev.off()
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

matplotlib画图

复制代码
    import matplotlib.pyplot as plt
    x = list(fanal.keys())
    y = list(fanal.values())
    plt.plot(x, y)
    plt.ylabel('frequency')
    plt.xlabel('location')
    plt.title('CG of reads')
    #plt.text(6, .15, r'$\mu=100,\ \sigma=15$')
    plt.show()
    
      
      
      
      
      
      
      
      
      
    
复制代码
8.16
    
      
    

全部评论 (0)

还没有任何评论哟~