把《Python生物信息学数据管理》这本书看完了,然后也写了一些笔记,和大家分享一下。
我感觉这本书比较适合有一点Python基础的同学,所以可以先看:Python应该要会一点吧。这篇笔记也是前一篇笔记的相互补充,然后书本上的一些知识点我就跳过啦(甚至跳过了一些章节)。
我也加入了一些自己的探索和思考在里面,希望能够记录一些更为实用的知识。
import sys
print(sys.version) #我的Python解释程序的版本信息
----------------------------------
3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)]
下面有些包可能会因为版本原因等各种问题而难以安装,大家可以尝试用conda来装包。
先安装anaconda3:https://mirrors.tuna.tsinghua.edu.cn/help/anaconda/
。
注意:
最后再配置一下解释器就可以了
pycharm专业版及一堆大家可能用得到的软件可以在这里面找找:#小程序://冰裤袋/Tfgc07Giqz1Omjs
。
装包遇到报错是普遍情况,大部分原因都是因为版本问题。
Python中的算术运算符
一些math模块中定义的重要函数
insulin = "GIVEQCCTSICSLYQLENYCNFVNQHLCGSHLVEALYLVCGERGFFYTPKT" #胰岛素序列
for amino_acid in "ACDEFGHIKLMNPQRSTVWY": #氨基酸
number = insulin.count(amino_acid) #计算每一个氨基酸在insulin中的数量
print (amino_acid, number)
----------------------------------
A 1
C 6
...
W 0
Y 4
# 从'AGCT'中抽取10个字符
import random
alphabet = "AGCT"
sequence = ""
for i in range(10): #0~9,差一索引
index = random.randint(0, 3)
sequence = sequence + alphabet[index]
print(sequence)
----------------------------------
GCTTCTGGTA #每一次打印出来的结果应该都不一样
#另一种方法
#可重复抽取alphabet中字符
sequence = ""
a=sequence.join([random.choice(alphabet) for i in range(10)])
print(a) #用join函数使之返回字符串类型
----------------------------------
CGGGACGGAA
#不重复抽取alphabet中字符
b = random.sample(alphabet, 4)
print(b) #b为list
----------------------------------
['A', 'G', 'T', 'C']
text = str(100) #处理浮点数时会降低可读性
type(text)
----------------------------------
<class 'str'>
#字符串格式化
'Result:%3i' % (17) #%3i表示格式化为三位的整数
'%8.3f' % (12.3456) #%8.3f表示总字符数为8,小数位数为3的浮点数。
'Hello,%s' % ('Hello,E.coli') #%s表示插入字符串
#%10s表示插入10个字符,且默认为右对齐
#%-10s表示插入10个字符,左对齐
----------------------------------
'Result: 17'
'12.346'
'Hello,E.coli'
#例:
'text:%25s numbers:%4i%4i%5.2f' %('right-justified',1,2,3)
----------------------------------
'text: right-justified numbers: 1 2 3.00'
str.format参考:https://www.runoob.com/python/att-string-format.html
注意:0和空对象对应的布尔值是False
#集合是唯一元件的无序组合,不含重复元素
data_a = set([1, 2, 3, 4, 5, 6])
#等价于data_a = {1, 2, 3, 4, 5, 6}
#注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
#也等价于data_a = set([1, 1, 2, 3, 4, 5, 6])
data_b = set([1, 5, 7, 8, 9])
#list类型数据需先set()转换成set类型才能进行下述代码
a_and_b = data_a.intersection(data_b) #交集
a_not_b = data_a.difference(data_b) #差:取出data_a独有的元素
b_not_a = data_b.difference(data_a) #取出data_b独有的元素
a_or_b = data_a.union(data_b) #并集
a_xor_b = data_a.symmetric_difference(data_b) #对称差:取出不同时存在于二者的元素
print(a_and_b)
print(a_not_b)
print(b_not_a)
print(a_or_b)
print(a_xor_b)
----------------------------------
{1, 5}
{2, 3, 4, 6}
{8, 9, 7}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{2, 3, 4, 6, 7, 8, 9}
import functools as f #reduce()函数已转移至该模块中(Python3.X)
a = {1, 2, 3, 4, 5}
b = {2, 4, 6, 7, 1}
c = {1, 4, 5, 9}
triple_set = [a, b, c]
common = f.reduce(set.intersection, triple_set)
#用传给 reduce 中的函数 intersection 先对triple_set中的、b进行操作,
#得到的结果再与c用 intersection 函数运算,最后得到一个结果。
print(common)
----------------------------------
{1, 4}
可对表进行的操作
#像Rstudio一样查看表格
import pandas as pd
table = [
[0.16, 0.038, 0.044, 0.040],
[0.33, 0.089, 0.095, 0.091],
[0.66, 0.184, 0.191, 0.191],
[1.00, 0.280, 0.292, 0.283],
[1.32, 0.365, 0.367, 0.365],
[1.66, 0.441, 0.443, 0.444]
]
B = pd.DataFrame(table)
#结果如下图
pd.DataFrame(table)
用于存储表的所有方法:嵌套列表、嵌套字典、二者混合
#这个好用,有轮子干嘛不用呢?
import pandas as pd
list1 = [[1,2,3],[4,5,6]]
df = pd.DataFrame(list1)
df.to_csv("test.csv",sep=',',header=False,index=False)
ASCII排序次序图。备注:数字位于字母之前,大写字母位于小写字母之前
data = ['ACCTGGCCA', 'ACTG', 'TACGGCAGGAGACG', 'TTGGATC']
bylength = sorted(data, key=lambda x:len(x))
#lambda 函数又称匿名函数,不包括 return语句,而是包括一个表达式,
#而且总会返回该表达式的值。
#可以在任何地方定义lambda函数,即便是在未分配名称的另一个函数的参数中。
print(bylength)
----------------------------------
['ACTG', 'TTGGATC', 'ACCTGGCCA', 'TACGGCAGGAGACG']
import pandas as pd
c=pd.read_table('random_distribution.tsv',header=None)
#这个tsv文件在文末的相关资料中,该文件没有表头,所以header=None
table_sorted = c.sort_values([0,1],ascending=False)
#按表格的第1、2列进行降序排序
print(table_sorted.shape) #查看dataframe的维度
print(table_sorted.head())#查看dataframe的前n行,默认n=6
----------------------------------
(1001, 7) #1001行,7列
0 1 2 3 4 5 6
555 6237 135 0.021645 53 0.008498 283 0.045374
631 6232 102 0.016367 56 0.008986 288 0.046213
656 6216 76 0.012227 50 0.008044 256 0.041184
正则表达式模式用到的字符
re模块方法
正则表达式编译标志
#例如:
import re
seq = 'RQSAMGSNKSKPKDASQRRRSLEPAENVHGAGGGAFPASQRPSKPrrsl'
pattern = re.compile('R.[ST][^P]',re.I)
#匹配以'R'开头,后一个字符为任意,接下来的字符为'S'或'T',最后不以'P'结尾的字符串。
#'re.I'表示不区分大小写
matches = pattern.findall(seq)
#找到seq中相匹配的所有字符串
print(matches)
----------------------------------
['RQSA', 'RRSL', 'RPSK', 'rrsl']
重复:*+?{}
Python结构图
本章主要介绍了一下rpy2的使用方法,因为版本原因,我没安装上这个包。但是我们可以通过安装插件R Language for Intellij
来实现在pycharm中运行R。
R Language for Intellij
在项目中配置一下R解释器的位置
上图就是pycharm中R界面,感觉也还挺好的,就是初始打开的时候,载入相关程序会多花一点时间。
和Rstudio相比,我更喜欢pycharm的写代码的界面,但是好像需要在某个项目中才能正确地打开pycharm。Rstudio就比较随意了,它的解释器路径相对固定,不管在哪个路径下打开R文件,都能直接跑。
比如我们想创建一个名为neuroimaging的包,我们需要将模块存储在同一个地方,就可以将模块集合成包。
文件夹的目录neuroimaging/ #该目录下包含我们所写的模块
neuron_count.py
shrink_images.py
_init_.py #为了让包可以导入,需要添加该文件
#该文件可以是空的
#_init_.py文件可由以下三个命令自动导入
import neuroimaging
from neuroimaging import neuron_count
from neuroimaging.shrink_images import *
#我找到了一个感觉比较好的画图包:plotly
#运行下面的代码需要先用pip安装plotly和plotly-express
#找了一个plotly画图的例子:
import plotly_express as px #这个包里有很多数据可以用来画图
gap = px.data.gapminder().query("year == 2002")
fig = px.scatter(
gap # 绘图数据
,x="gdpPercap" # x轴
,y="lifeExp" # y轴
,color="continent" # 颜色参数
,size="pop" # 点的大小
,size_max=60 # 点的最大值
)
fig.show()
#画出了一张交互式的图。
气泡图
更多图表参考:
https://github.com/plotly/plotly.py
https://plotly.com/python/
绘制和处理图像的Python命令
from PIL import Image
image = Image.open('color.png', 'r')
label = Image.open('label.png', 'r')
image.paste(label, (40, 460)) #(40, 460)为label的位置,默认为(0,0)
#(0,0)为image的左上角。
image.save('combined.png')
#结果如下
from PIL import Image
image = Image.open('color.png', 'r')
bw_image = Image.new('LA', image.size, (255, 255)) #创建一张空图像
#'LA'表示单色模式
#(255, 255)为图像填充的颜色
bw_image.paste(image, (0, 0))
bw_image.save('black_white.png')
更多biopython知识参考:
https://biopython.org/wiki/Documentation
#代码有所改变,参考:https://biopython.org/wiki/Alphabet
from Bio import Seq
from Bio.SeqRecord import SeqRecord
from Bio import SeqIO
# read the input sequence
dna = open("hemoglobin-gene.txt").read().strip() #该文件内容为一条DNA编码序列
dna = Seq.Seq(dna)
#Seq对象为不可更改序列,mutableSeq对象为可变序列对象
# transcribe and translate
mrna = dna.transcribe() #转录
protein = mrna.translate() #翻译
# write the protein sequence to a file
protein_record = SeqRecord(protein, id='sp|P69905.2|HBA_HUMAN',
description="Hemoglobin subunit alpha, Homo sapiens")
outfile = open("HBA_HUMAN.fasta", "w")
SeqIO.write(protein_record, outfile,"fasta")
#SeqIO.write可将多个SeqRecord对象写入指定文件
outfile.close()
HBA_HUMAN.fasta #该输出文件内容如下
----------------------------------
>sp|P69905.2|HBA_HUMAN Hemoglobin subunit alpha, Homo sapiens
MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHG
KKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTP
AVHASLDKFLASVSTVLTSKYR*
Biopython访问NCBI网络服务的模块又称Entrez,用来访问和下载NCBI数据记录。近一步的解析文献记录,需要一个模块Bio.Medline中的特定解析器。
#具体文档可参考:https://www.ncbi.nlm.nih.gov/books/NBK25499/
from Bio import Entrez
from Bio import Medline
keyword = "PyCogent"
# search publications in PubMed
Entrez.email = "my_email@address.com"
#如果出现问题,NCBI可通过邮件联系你,但是这个是非强制性的
handle = Entrez.esearch(db="pubmed", term=keyword) #在NCBI中搜索
#更多db可参考:https://www.ncbi.nlm.nih.gov/books/NBK25497/table/chapter2.T._entrez_unique_identifiers_ui/?report=objectonly
record = Entrez.read(handle)
pmids = record['IdList']
print (pmids)
# retrieve Medline entries from PubMed
handle = Entrez.efetch(db="pubmed", id=pmids, rettype="medline", retmode="text")
#从NCBI服务器上下载记录
medline_records = Medline.parse(handle) #解析下载的记录
#如果需要解析单个记录,则可使用Medline.read()函数,而不是Medline.parse()。
records = list(medline_records)
n = 1
for record in records:
if keyword in record["TI"]:
print (n, ')', record["TI"])
n += 1
----------------------------------
['22479120', '18230758', '17708774']
1 ) Abstractions, algorithms and data structures for structural bioinformatics in PyCogent.
2 ) PyCogent: a toolkit for making sense from sequence.
#Biopython提供了一个模块(称为ExPASy)来访问SwissProt数据库和其他的Expasy资源
from Bio import ExPASy
from Bio import SeqIO
#下述代码只能同时对一个SwissProt的AC进行处理,
handle = ExPASy.get_sprot_raw("P04637")
seq_record = SeqIO.read(handle, "swiss")
print (seq_record.id)
print (seq_record.description)
#可用for循环逐个检索和解析它们。
out = open('myfile.fasta','w')
fasta = SeqIO.write(seq_record, out, "fasta")
out.close()
#Bio.PDB包可用来从网络上检索大分子结构,读写PDB文件,计算原子间的距离和角度,叠加结构。
from Bio import PDB
from Bio.PDB import PDBIO
pdbl = PDB.PDBList()
pdbl.retrieve_pdb_file("2DN1") #下载pdb结构
parser = PDB.PDBParser() #解析pdb结构
structure = parser.get_structure("2DN1", "dn/pdb2dn1.ent")
#Structure对象是一个容器,存储PDB数据项中的结构信息,
#这个层次结构可以被简写为SMCRA(Structure→Model(s)→Chain(s)→Residues→Atoms)。
#parser = MMCIFParser() #解析mmCIF文件
#structure = parser.get structure("2DN1","2DN1.cif")
for model in structure:
for chain in model:
print (chain) #打印链
for residue in chain:
print (residue.resname, residue.id[1]) #打印残基及其序列标识
for atom in residue:
print (atom.name, atom.coord) #打印原子及其坐标
# write pdb file
io = PDBIO()
io.set_structure(structure)
io.save('my_structure.pdb') #将structure对象保存到文件
from Bio import PDB
parser = PDB.PDBParser()
structure = parser.get_structure("2DN1","dn/pdb2dn1.ent")
#pdb2dn1.ent文件在/dn文件夹中
atom1 = structure[0]['A'][2]['CA']
atom2 = structure[0]['A'][3]['CA']
dist = atom1 - atom2
print (dist)
----------------------------------
3.7660766
修改变量
字符串函数
找出模块中有什么
http://matplotlib.org/
这是一个强大的创建图表的库,是Python科学库(SciPy)的一部分。www.pythonware.com/products/pil/
PIL是一个操纵图片的通用库。http://pycogent.org/
PyCogent是一个有很多功能的生物学库,很多方面类似Biopython,但它的优势是处理RNA和系统发生学分析。(在windows上比较难运行)http://iimcb.genesilico.pl/moderna/
ModeRNA是一个检察、处理和建立RNA结构三维模型的Python库。这本书里面也提到了很多的生信相关软件,
我主要记录了一些python的相关知识。
很多知识我也正在学习中。
理论加实践才是学习知识的最好方法,学习了这些Python基础我们就可以放手去做了,在后续的实践中不断完善自己的不足之处。