计算连续的字母和连字符并将它们编码为 运行 长度

Counting consecutive alphabets and hyphens and encode them as run length

如何编码我的带连字符的 fasta 格式字符串以将所有连续的核苷酸和连字符以及 encode them as run length.

分组

将我的序列视为 "ATGC----CGCTA-----G---"。该字符串具有 Nucleotide 序列,后跟连字符序列。我试图将所有连续的核苷酸分组为字母 M 并将连续的连字符分组为字母 D 并在其前面加上子序列的大小。

这种编码的最终结果应该是4M4D5M5D1M3D

下图进一步说明

ATGC----CGCTA-----G---
 |   |    |    |  |  |
 V   V    V    V  V  V
4M   4D  5M    5D 1M 3D

当我使用 Counterlist.count() 时,我得到 "M":10 "D":12:

from collections import Counter

seq="ATGC----CGCTA-----G---"

M=0
D=0   

cigar=[]

for char in seq:    
    if char.isalpha():
        M+=1
        cigar.append("M")   
    else:
        D+=1
        cigar.append("D")

print Counter(cigar)

这个问题很适合itertools.groupby

实施

from itertools import groupby
''.join('{}{}'.format(len(list(g)), 'DM'[k]) 
        for k, g in groupby(seq, key = str.isalpha))

输出 '4M4D5M5D1M3D'

说明

值得注意的是,关键功能在这里至关重要。根据序列是否为字母表对序列进行分组。完成后,应该直接统计每个组的大小并从关键元素中找出组的类型。

代码的一些解释

  • 'DM'[k]:这只是表示 "M" if k == True else "D"
  • 的一种巧妙方式
  • len(list(g)):确定每个组的大小。或者,它可以写成 sum(1 for e in g)
  • '{}{}'.format:字符串格式化以创建连续频率和类型的串联
  • ''.join(: 将列表元素作为字符串序列加入。

经典方法:

seq="ATGC----CGCTA-----G---"

def MD(c):
    if c.isalpha():return "M"
    else : return "D"

count=1
string=""
for i in range(len(seq)-1):
    if MD(seq[i])==MD(seq[i+1]): count+=1
    else: 
        string=string+str(count)+MD(seq[i])
        count=1
string=string+str(count)+MD(seq[-1])
print string
import re
seq='ATGC----CGCTA-----G---'

output = ''
for section in re.split('(-*)', seq):
    if section.isalpha():
        output += str(len(section)) + 'M'
    elif section !='':
        output += str(len(section)) + 'D'
print output