一:在蛋白质序列中探索磷酸化模体
在蛋白质序列中搜索磷酸化motif,并返回第一个出现的motif
import re
seq = "VSVLTMFRYAGWLDRLYMLVGTQLAAIIHGVALPLMMLI"
regexp = re.compile('[ST]Q') ##设定一个正则表达对象来匹配SQ或TQ
match = regexp.search(seq) ##若序列中包含regexp子串,则返回Match对象,否则返回None。
if match:
print(match.group(),match.start(),match.end())
else:
print('no match')
TQ 21 23
search()函数扫描字符串并寻找正则表达式第一次匹配的位置,需要注意的是search()方法返回的是Match object而不是直接返回字符串
如果想找到所有的匹配该怎么做?
这里用到findall()和finditer();
findall()返回所有匹配的子字符串列表(list)
finditer()返回所有匹配对象的迭代器形式,可以用for循环实现遍历
#### findall()
import re
seq = "VSVLTMFRYAGWLDRLYMLVGTQLAAIIHGVALPLMMLI"
regexp = re.compile('[MY]M')
match = regexp.findall(seq)
if match:
print(match)
else:
print('no match')
['YM', 'MM']
#### finditer()
import re
seq = "VSVLTMFRYAGWLDRLYMLVGTQLAAIIHGVALPLMMLI"
regexp = re.compile('[MY](.)L')
match = regexp.finditer(seq)
if match:
for iter in match:
print(iter.group())
print(iter.span())
print(iter.start())
print(iter.end())
else:
print('no match')
YML
(16, 19)
16
19
MML
(35, 38)
35
38
1.分组
有时候会将一个正则表达式分为若干个子组,来匹配不同的部分,比如想要知道.匹配了什么氨基酸,可以将她用圆括号括起来以创建一个组,然后使用group()方法得到相匹配的氨基酸类型。
- group()方法不填写参数或参数为0,则返回完全匹配的字符串;子组从1开始自左向右编号。
import re
seq = "VSVLTMFRYAGWLDRLYMLVGTQLAAIIHGVALPLMMLI"
regexp = re.compile('[NY](.)(L)') ##用圆括号括起来以创建一个组,这里两个子组
match = regexp.finditer(seq)
if match:
for iter in match:
print(iter.group())
print(iter.group(1)) ##打印(.)匹配的
print(iter.group(2)) ##打印(L)匹配的
else:
print('no match')
YML
M
L
- 也可以向group()方法中传递多个参数,得到各个子组的元组。
print(iter.group(2,1))
('L', 'M')
- 也可以用groups()方法返回一个包含所有与子组相关的元组。
print(iter.groups())
('M', 'L')
2.修改字符串
re模块提供了三种修改字符串的方法:
- split(s)
- sub(r,s,[c])
- subn(r,s,[c])
split(s)方法将分割符合正则表达式的字符串,产生一个列表。在下面的例子中,实现了一个字符串在|处分割,又因为|是元字符所以需要加反斜杠转义。 - split()
import re
separator = re.compile('\|')
annotation = 'ATOM:CA|RES:ALA|CHAIN:B|NUMRES:166'
columes = separator.split(annotation)
print(columes)
['ATOM:CA', 'RES:ALA', 'CHAIN:B', 'NUMRES:166']
- sub(r,s,[c])返回新字符串
import re
separator = re.compile('\|')
annotation = 'ATOM:CA|RES:ALA|CHAIN:B|NUMRES:166'
new_annotation = separator.sub('@',annotation)
print(new_annotation)
ATOM:CA@RES:ALA@CHAIN:B@NUMRES:166
- 3.subn(r,s,[c]) 返回一个含两个元件的tuple,第一个为新字符串,第二个为替换的数量
import re
separator = re.compile('\|')
annotation = 'ATOM:CA|RES:ALA|CHAIN:B|NUMRES:166'
new_annotation = separator.subn('@',annotation)
print(new_annotation)
('ATOM:CA@RES:ALA@CHAIN:B@NUMRES:166', 3)