如何使用Python finditer获取重叠模式?

时间:2014-04-11 16:03:44

标签: python regex pattern-matching fasta

我正在使用一个在fasta文件中搜索模式的python脚本。它工作得很好,但它没有返回重叠的字符串。不幸的是,我对潜在的重叠字符串感兴趣。由于我不是程序员(我只是想学习Python),我想知道是否有人可以修改脚本以找到重叠的字符串。我认为正则表达式模块可以做到,但我试图在我的计算机(Windows)上安装它而没有成功。我明白了:

C:\Python33>regex-2014.02.19>python setup.py install
running install
running build
running build_py
runnning built_ext
building'_regex' extension
error:Unable to find vcvarsall.bat

对我来说,使用修改过的脚本会更容易。所以这是我的剧本:

import re
import sys

psq_re_f= re.compile('G{3,}.{1,7}?G{3,}.{1,7}?G{3,}.{1,7}?G{3,}') #((?<=G)[^G]|(?<!G).)
psq_re_r= re.compile('C{3,}.{1,7}?C{3,}.{1,7}?C{3,}.{1,7}?C{3,}') #((?<=C)[^C]|(?<!C).)


filename = input('Enter the name of the input fasta file: ')
ref_seq_fh = open(filename)

outputfileg = open("strelkaindels_quadg.txt",'wt')
outputfilec = open("strelkaindels_quadc.txt",'wt')

outputfileg.write('#\tID\tEntry Length\tStart\tEnd\tLength\tStrand\tSequence\n')
outputfilec.write('#\tID\tEntry Length\tStart\tEnd\tLength\tStrand\tSequence\n')

count = 0
ref_seq = []
line = (ref_seq_fh.readline()).strip()
chr = re.sub('^>', '', line)
chr1 = chr.split (":")
#line = (ref_seq_fh.readline()).strip()
while True:
    while line.startswith('>') is False:
        ref_seq.append(line)
        line = (ref_seq_fh.readline()).strip()
        if line == '':
            break
    ref_seq = ''.join(ref_seq)
    for m in re.finditer(psq_re_f, ref_seq):
        count=count+1
        outputfileg.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' %(count, chr1[0], len(ref_seq), m.start(), m.end(), len(m.group(0)), '+', m.group(0))+'\n')
    for m in re.finditer(psq_re_r, ref_seq):
        count=count+1
        outputfilec.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' %(count, chr1[0], len(ref_seq), m.start(), m.end(), len(m.group(0)), '-', m.group(0))+'\n')
    chr = re.sub('^>', '', line)
    chr1 = chr.split (":")
    ref_seq = []
    line= (ref_seq_fh.readline()).strip()
    if line == '':
        break


outputfileg.close()
outputfilec.close()

最后一个在生物学中广泛使用的fasta文件(代表核苷酸序列的基于文本的格式)的例子:

>id_1
agatagatgatagatatagagagcgcgctagatcgatcgatcgagtcgatcgcgcggggggcccctctctctctatagggacatacga
>id_2
agacatcagatacagagatatttacataacaagagatacag
>id_3
cgctctagctcctcctctcgcgtagctagctctctctaacatgattagaattcagatcgatcgatcgatggttttttttctctct
and so on...

例如,让我们想象以下序列:

GGGTGGGTGGGCGGGAGGG

脚本将只返回此字符串:

GGGTGGGTGGGCGGG

但我也想得到那个:

GGGTGGGCGGGAGGG

1 个答案:

答案 0 :(得分:0)

您可以尝试使用正面的looakehead:

(?=(G{3,}.{1,7}?G{3,}.{1,7}?G{3,}.{1,7}?G{3,}))

regex101 demo

在您的代码中,您必须将您的论坛更改为.group(1),但m.end()将与m.start()相同,因此您可能会稍微解决一下,也许我的使用len()

for m in re.finditer(psq_re_f, ref_seq):
    count=count+1
    outputfileg.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' % (count,
                      chr1[0], len(ref_seq), m.start(),
                      m.start() + len(m.group(1)), len(m.group(1)),
                      '+',m.group(1))+'\n')