在与不同字符串列表匹配的位置拆分字符串列表

时间:2016-08-31 00:28:42

标签: python string split

我写了一个小程序来执行以下操作。我想知道是否有一个明显更优化的解决方案:

1)取2个字符串列表。通常,第二个列表中的字符串将比第一个列表中的字符串长,但这不能保证

2)返回从第二个列表派生的字符串列表,该列表已从第一个列表中删除了任何匹配的字符串。因此,该列表将包含< =第二个列表中字符串长度的字符串。

下面我展示了我正在谈论的图片示例: basic outline of what should happen

到目前为止,我这就是我所拥有的。它似乎工作正常,但我只是好奇是否有一个我更缺失的更优雅的解决方案。顺便说一句,我正在跟踪字符串每个开头和结尾的“位置”,这对于该程序的后续部分非常重要。

def split_sequence(sequence = "", split_seq = "", length = 8):
    if len(sequence) < len(split_seq):
        return [],[]
    split_positions = [0]
    for pos in range(len(sequence)-len(split_seq)):
        if sequence[pos:pos+len(split_seq)] == split_seq and pos > split_positions[-1]:
            split_positions += [pos, pos+len(split_seq)]
    if split_positions[-1] == 0:
        return [sequence], [(0,len(sequence)-1)]
    split_positions.append(len(sequence))
    assert len(split_positions) % 2 == 0
    split_sequences = [sequence[split_positions[_]:split_positions[_+1]] for _ in range(0, len(split_positions),2)]
    split_seq_positions = [(split_positions[_],split_positions[_+1]) for _ in range(0, len(split_positions),2)]
    return_sequences = []
    return_positions = []
    for pos,seq in enumerate(split_sequences):
        if len(seq) >= length:
            return_sequences.append(split_sequences[pos])
            return_positions.append(split_seq_positions[pos])
    return return_sequences, return_positions





def create_sequences_from_targets(sequence_list = [] , positions_list = [],length=8, avoid = []):
    if avoid:
        for avoided_seq in avoid:
            new_sequence_list = []
            new_positions_list = []
            for pos,sequence in enumerate(sequence_list):
                start = positions_list[pos][0]
                seqs, positions = split_sequence(sequence = sequence, split_seq = avoided_seq, length = length)
                new_sequence_list += seqs
                new_positions_list += [(positions[_][0]+start,positions[_][1]+start) for _ in range(len(positions))]
        return new_sequence_list, new_positions_list

示例输出:

In [60]: create_sequences_from_targets(sequence_list=['MPHSSLHPSIPCPRGHGAQKA', 'AEELRHIHSRYRGSYWRTVRA', 'KGLAPAEISAVCEKGNFNVA'],positions_list=[(0, 20), (66, 86), (136, 155)],avoid=['SRYRGSYW'],length=3)
Out[60]: 
(['MPHSSLHPSIPCPRGHGAQKA', 'AEELRHIH', 'RTVRA', 'KGLAPAEISAVCEKGNFNVA'],
 [(0, 20), (66, 74), (82, 87), (136, 155)])

2 个答案:

答案 0 :(得分:4)

让我们定义此字符串,s以及要删除的字符串列表list1

>>> s = 'NowIsTheTimeForAllGoodMenToComeToTheAidOfTheParty'
>>> list1 = 'The', 'Good'

现在,让我们删除这些字符串:

>>> import re
>>> re.split('|'.join(list1), s)
['NowIs', 'TimeForAll', 'MenToComeTo', 'AidOf', 'Party']

上述功能之一是list1中的字符串可以包含正则表达式活动字符。这也可能是不合需要的。正如John La Rooy在评论中指出的那样,list1中的字符串可以通过以下方式处于非活动状态:

>>> re.split('|'.join(re.escape(x) for x in list1), s)
['NowIs', 'TimeForAll', 'MenToComeTo', 'AidOf', 'Party']

答案 1 :(得分:4)

使用正则表达式可以简化代码,但它可能会更高效,也可能不会更高效。

>>> import re
>>> sequence_list = ['MPHSSLHPSIPCPRGHGAQKA', 'AEELRHIHSRYRGSYWRTVRA', 'KGLAPAEISAVCEKGNFNVA'],positions_list=[(0, 20), (66, 86), (136, 155)]
>>> avoid = ['SRYRGSYW']
>>> rex = re.compile("|".join(map(re.escape, avoid)))

得到这样的位置(你需要将偏移添加到这些位置)

>>> [[j.span() for j in rex.finditer(i)] for i in sequence_list]
[[], [(8, 16)], []]

获取像这样的新字符串

>>> [rex.split(i) for i in sequence_list]
[['MPHSSLHPSIPCPRGHGAQKA'], ['AEELRHIH', 'RTVRA'], ['KGLAPAEISAVCEKGNFNVA']]

或展平列表

>>> [j for i in sequence_list for j in rex.split(i)]
['MPHSSLHPSIPCPRGHGAQKA', 'AEELRHIH', 'RTVRA', 'KGLAPAEISAVCEKGNFNVA']