2015-04-01 104 views
0

我试图搜索的核苷酸序列为用户定义的图案,使用正则表达式(仅A,C,G,T组成)搜索模式:的Python:使用字符串变量如在正则表达式

相关代码如下:

match = re.match(r'{0}'.format(pattern), sequence) 

比赛总是返回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 

不是很Python的,我知道......

+0

你可以发布你的测试用例吗? – letsc 2015-04-01 22:52:11

+0

你是指我在寻找的序列吗?它真的很长......就像超过1000个字符 – user3472351 2015-04-01 22:53:12

+0

当你对模式进行硬编码时会发生什么? – 2015-04-01 22:53:26

回答

2

这应该很好地工作:

>>> tgt='AGAGAGAGACGTACACAC' 
>>> re.match(r'{}'.format('ACGT'), tgt) 
>>> re.search(r'{}'.format('ACGT'), tgt) 
<_sre.SRE_Match object at 0x10a5d6920> 

我想这可能是因为你的意思是使用搜索VS匹配您发布的代码


提示:

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' 
+0

谢谢,这很有效。将接受你的答案,当stackoverflow允许我这样做:)(由于某种原因六分钟) – user3472351 2015-04-01 23:00:15

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' 
相关问题