2015-04-01 36 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' 
相關問題