2015-02-11 33 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