我尝试使用正则表达式搜索用户定义模式的核苷酸序列(仅由A,C,G,T组成):
相关代码如下:
match = re.match(r'{0}'.format(pattern), sequence)
match总是返回None,我需要它返回与用户查询匹配的序列部分...
我做错了什么?
编辑:这是我构建搜索模式的方式:
askMotif = raw_input('Enter a motif to search for it in the sequence (The wildcard character ‘?’ represents any nucleotide in that position, and * represents none or many nucleotides in that position.): ')
listMotif= []
letterlist = ['A','C','G','T', 'a', 'c','g','t']
for letter in askMotif:
if letter in letterlist:
a = letter.capitalize()
listMotif.append(a)
if letter == '?':
listMotif.append('.')
if letter == '*':
listMotif.append('*?')
pattern = ''
for searcher in listMotif:
pattern+=searcher
不是非常pythonic,我知道......
答案 0 :(得分:2)
这应该可以正常工作:
>>> tgt='AGAGAGAGACGTACACAC'
>>> re.match(r'{}'.format('ACGT'), tgt)
>>> re.search(r'{}'.format('ACGT'), tgt)
<_sre.SRE_Match object at 0x10a5d6920>
我认为这可能是因为你的意思是使用搜索与匹配
提示您发布的代码:
prompt='''\
Enter a motif to search for it in the sequence
(The wildcard character '?' represents any nucleotide in that position,
and * represents none or many nucleotides in that position.)
'''
pattern=None
while pattern==None:
print prompt
user_input=raw_input('>>> ')
letterlist = ['A','C','G','T', '?', '*']
user_input=user_input.upper()
if len(user_input)>1 and all(c in letterlist for c in user_input):
pattern=user_input.replace('?', '.').replace('*', '.*?')
else:
print 'Bad pattern, please try again'
答案 1 :(得分:1)
re.match()
仅在序列开头匹配。也许你需要re.search()
?
>>> re.match(r'{0}'.format('bar'), 'foobar').group(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> re.search(r'{0}'.format('bar'), 'foobar').group(0)
'bar'