让字符串为"AAAGQWERTYUIOPAGCTHJKLAAAGZXCVBNMAGCT"
。我想找到AAAG和AGCT之间的字符串。
我希望输出为["QWERTYUIOP","ZXCVBNM"]
,即字符串列表。
如何使用正则表达式或类似技术来做到这一点?
我尝试过
def find_distances_between_motifs(positions1, positions2, motif_length1):
diff1 = []
diff2 = []
pos2 = 0
flag = 0
for pos1 in range(len(positions1)):
if pos2 >= len(positions2):
break
if flag == 1:
flag = 0
pos1 -= 1
if positions2[pos2] - positions1[pos1] > 30:
diff1.append(NaN)
diff2.append(NaN)
continue
elif positions2[pos2] - positions1[pos1] < 1:
pos2 += 1
diff2.append(NaN)
flag = 1
elif pos1 < len(positions1) - 1 and positions1[pos1+1] > positions2[pos2]:
diff1.append(positions[pos2] - positions[pos1] - motif_length1)
diff2.append(pos2)
pos2 += 1
else:
continue
return diff1, diff2
我想返回两个数组-一个数组的位置在两个基序之间,而第二个数组的第二个基序将给出先前的距离。
答案 0 :(得分:7)
使用正则表达式。 re.findall
和Lookbehind&Lookahead
例如:
import re
s = "AAAGQWERTYUIOPAGCTHJKLAAAGZXCVBNMAGCT"
print( re.findall(r"(?<=AAAG).*?(?=AGCT)", s))
输出:
['QWERTYUIOP', 'ZXCVBNM']
答案 1 :(得分:1)
如果您不想使用正则表达式,那么我已经编写了代码。它有点复杂,但是如果您仔细研究它,那么您将会理解。
def addd(llist,word,word2):
xx1 = sum([[i, word] for i in llist], [])[:-1]
try:iii = xx1.index(word2);del xx1[iii]
except:pass
return xx1
a,output = addd("AAAGQWERTYUIOPAGCTHJKLAAAGZXCVBNMAGCT".split("AAAG"),"St4rT",""),[]
for i,x in enumerate(a):
if "AGCT" in x:
output.append(addd(x.split("AGCT"),"3nD.",""))
else:output.append(x)
total = []
for i in output:
if isinstance(i,list):total+=i
elif isinstance(i,str):total.append(i)
output,typ = [],0
for x,i in enumerate(total):
if typ == 0 and i == "St4rT":
try:output.append(total[x+1]);typ = 1
except:pass
elif typ == 1 and i == "3nD.":typ = 0
print(output)
输出:
['QWERTYUIOP', 'ZXCVBNM']