在python中的特定模式中剪切字符串

时间:2017-04-12 09:34:37

标签: python string bioinformatics

我的字符串长度只有4个字符,分别是A,T,G和C'。我有模式' GAATTC'在给定的字符串中多次出现。我必须按照这种模式的间隔剪切字符串。 例如,对于字符串,' ATC GAATTC ATA',我应该得到

的输出
  • string one - ATCGA
  • string two - ATTCATA

我是使用Python的新手,但我提出了以下(不完整的)代码:

seq = seq.upper()
str1 = "GAATTC"
seqlen = len(seq)
seq = list(seq)

for i in range(0,seqlen-1):
    site = seq.find(str1)
    print(site[0:(i+2)])

任何帮助都会非常感激。

5 个答案:

答案 0 :(得分:3)

这是一个简单的解决方案:

seq = 'ATCGAATTCATA'
seq_split = seq.upper().split('GAATTC')
result = [ 
    (seq_split[i]  + 'GA') if i % 2 == 0 else ('ATTC' + seq_split[i]) 
    for i in range(len(seq_split)) if len(seq_split[i]) > 0 
]

结果:

print(result)
['ATCGA', 'ATTCATA']

答案 1 :(得分:2)

首先让我们提出使用find的想法,这样你就可以找出错误。

seq = 'ATCGAATTCATAATCGAATTCATAATCGAATTCATA'
seq = seq.upper()
pattern = "GAATTC"
split_at = 2
seqlen = len(seq)
i = 0

while i < seqlen:
    site = seq.find(pattern, i)
    if site != -1:
       print(seq[i: site + split_at])
       i = site + split_at
    else:
       print seq[i:]
       break

然而,python string是一种强大的替换方法,可以直接替换字符串的碎片。以下代码段使用replace方法在需要时插入分隔符:

seq = 'ATCGAATTCATAATCGAATTCATAATCGAATTCATA'
seq = seq.upper()
pattern = "GA","ATTC"
pattern1 = ''.join(pattern) # 'GAATTC'
pattern2 = ' '.join(pattern) # 'GA ATTC'
splited_seq = seq.replace(pattern1, pattern2) # 'ATCGA ATTCATAATCGA ATTCATAATCGA ATTCATA'
print (splited_seq.split())

我认为它更直观,应该比RE快(可能性能较低,具体取决于库和用法)

答案 2 :(得分:1)

BioPython有一个限制酶包,可以完全按照您的要求进行。

from Bio.Restriction import *
from Bio.Alphabet.IUPAC import IUPACAmbiguousDNA

print(EcoRI.site) # You will see that this is the enzyme you listed above

test = 'ATCGAATTCATA'.upper() # This is the sequence you want to search
my_seq = Seq(test, IUPACAmbiguousDNA()) # Create a biopython Seq object with our sequence

cut_sites = EcoRI.search(my_seq)

cut_sites包含确切切割输入序列的位置列表(这样GA位于左侧序列中,ATTC位于正确的序列中。

然后您可以使用以下方法将序列拆分为重叠群:

cut_sites = [0] + cut_sites # We add a leading zero so this works for the first
                            # contig. This might not always be needed.
contigs = [test[i:j] for i,j in zip(cut_sites, cut_sites[1:]+[None])]

您可以see this page了解有关BioPython的更多详情。

答案 3 :(得分:0)

我的代码有点草率,但是当你想迭代多次出现的字符串时你可以尝试这样的东西

def split_strings(seq):
    string1 = seq[:seq.find(str1) +2]
    string2 = seq[seq.find(str1) +2:]
    return string1, string2


test = 'ATCGAATTCATA'.upper()
str1 = 'GAATTC'

seq = test
while str1 in seq:
    string1, seq = split_strings(seq)
    print string1
print seq

答案 4 :(得分:0)

这是使用正则表达式模块的解决方案:

import re
seq = 'ATCGAATTCATA'
restriction_site = re.compile('GAATTC')
subseq_start = 0
for match in restriction_site.finditer(seq):
   print seq[subseq_start:match.start()+2]
   subseq_start = match.start()+2
print seq[subseq_start:]

输出:

ATCGA
ATTCATA