2015-02-11 69 views
0
String = n76a+q80a+l83a+i153a+l203f+r207a+s211a+s215w+f216a+e283l 

我希望腳本來看看一對在時間意義:Python的查找和具體情況而定替換/與函數

評估n76a + q80a。如果abs(76-80)< 10,則用'_'替換'+':否則不會改變任何內容。 然後評估q80a + l83a,然後做同樣的事情。

所需的輸出應該是:

n76a_q80a_l83a+i153a+l203f_r207a_s211a_s215w_f216a+e283l 

什麼,我試圖,

def aa_dist(x): 
if abs(int(x[1:3]) - int(x[6:8])) < 10: 
    print re.sub(r'\+', '_', x) 

with open(input_file, 'r') as alex: 
    oligos_list = alex.read() 
    aa_dist(oligos_list) 

這是我到這一點。我知道我的代碼只會將'+'全部替換爲'_',因爲它只評估第一對並替換全部。我應該怎麼做?

+0

是它總是 '+' 和小寫字母? – 2015-02-11 23:50:58

+0

是的。情況總是如此。 – 2015-02-11 23:57:30

+0

我認爲在'i153a + l203f'的情況下指數值會發生變化# – 2015-02-11 23:59:47

回答

2
import itertools,re 

my_string = "n76a+q80a+l83a+i153a+l203f+r207a+s211a+s215w+f216a+e283l" 
#first extract the numbers  
my_numbers = map(int,re.findall("[0-9]+",my_string)) 
#split the string on + (useless comment) 
parts = my_string.split("+") 

def get_filler((a,b)): 
    '''this method decides on the joiner''' 
    return "_" if abs(a-b) < 10 else '+' 

fillers = map(get_filler,zip(my_numbers,my_numbers[1:])) #figure out what fillers we need 
print "".join(itertools.chain.from_iterable(zip(parts,fillers)))+parts[-1] #it will always skip the last part so gotta add it 

是你可以做到這一點的一種方式......,也是毫無價值的意見

+0

謝謝!一般來說,我對編程確實很陌生,但我對itertool模塊並不熟悉。你能不能再詳細解釋下面兩行的內容呢?填充=地圖(get_filler,zip(my_numbers,my_numbers [1:]))#figure out what fillers we need print「」.join(ziprt(parts,fillers)))+ parts [-1 ] – 2015-02-12 01:02:43

+0

'itertools.chain'只需要一個2d列表並將其平滑...這是多種方法之一...上面的行將自己的數字列表拉下來以獲取相鄰數字對並將它們映射到一個函數決定+或_ – 2015-02-12 01:13:50

+0

謝謝!有用! – 2015-02-12 02:06:56

1

只通過re模塊的示例。

>>> s = 'n76a+q80a+l83a+i153a+l203f+r207a+s211a+s215w+f216a+e283l' 
>>> m = re.findall(r'(?=\b([^+]+\+[^+]+))', s)    # This regex would helps to do a overlapping match. See the demo (https://regex101.com/r/jO6zT2/13) 
>>> m 
['n76a+q80a', 'q80a+l83a', 'l83a+i153a', 'i153a+l203f', 'l203f+r207a', 'r207a+s211a', 's211a+s215w', 's215w+f216a', 'f216a+e283l'] 
>>> l = [] 
>>> for i in m: 
     if abs(int(re.search(r'^\D*(\d+)', i).group(1)) - int(re.search(r'^\D*\d+\D*(\d+)', i).group(1))) < 10: 
      l.append(i.replace('+', '_')) 
     else: 
      l.append(i) 
>>> re.sub(r'([a-z0-9]+)\1', r'\1',''.join(l)) 
'n76a_q80a_l83a+i153a+l203f_r207a_s211a_s215w_f216a+e283l' 

通過定義一個單獨的函數。

import re 
def aa_dist(x): 
    l = [] 
    m = re.findall(r'(?=\b([^+]+\+[^+]+))', x) 
    for i in m: 
     if abs(int(re.search(r'^\D*(\d+)', i).group(1)) - int(re.search(r'^\D*\d+\D*(\d+)', i).group(1))) < 10: 
      l.append(i.replace('+', '_')) 
     else: 
      l.append(i) 
    return re.sub(r'([a-z0-9]+)\1', r'\1',''.join(l)) 

string = 'n76a+q80a+l83a+i153a+l203f+r207a+s211a+s215w+f216a+e283l' 
print aa_dist(string) 

輸出:

n76a_q80a_l83a+i153a+l203f_r207a_s211a_s215w_f216a+e283l