创建与输入字符串大小相同的出现向量

时间:2012-04-09 09:38:39

标签: python-2.7

我是python的新手,需要一些帮助。

我有一个字符串,如ACAACGG

我现在想创建3个向量,其中元素是特定字母的计数。

例如,对于“A”,这将产生(1123333) 对于“C”,这将产生(0111222) 等

我不确定如何将计数结果放入字符串或向量中。 我相信这类似于计算字符串中字符的出现次数,但我不确定如何使字符串运行并将计数值放在每个点上。

作为参考,我正在尝试实现Burrows-Wheeler转换并将其用于字符串搜索。但是,我不确定如何为字符创建出现矢量。

def bwt(s):
  s = s + '$'
  return ''.join([x[-1] for x in
     sorted([s[i:] + s[:i] for i in range(len(s))])])

这给了我变换,我正在尝试为它创建出现向量。最终,我想用它来搜索DNA字符串中的重复。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

我不确定你想要什么类型的矢量,但是这里的函数返回listint

 In [1]: def countervector(s, char):
   ....:     c = 0
   ....:     v = []
   ....:     for x in s:
   ....:         if x == char:
   ....:             c += 1
   ....:         v.append(c)
   ....:     return v
   ....: 

 In [2]: countervector('ACAACGG', 'A')
 Out[2]: [1, 1, 2, 3, 3, 3, 3]

 In [3]: countervector('ACAACGG', 'C')
 Out[3]: [0, 1, 1, 1, 2, 2, 2]

此外,这是一个更短的方法,但它可能在长字符串上效率低下:

def countervector(s, char):
    return [s[:i+1].count(char) for i, _ in enumerate(s)]

我希望它有所帮助。

答案 1 :(得分:0)

这里承诺的是我写完的脚本。作为参考,我试图使用Burrows-Wheeler变换在DNA串中重复匹配。基本上,我们的想法是获取一段长度为M的DNA链,然后在该字符串中找到所有重复的DNA。因此,作为一个例子,如果我有奇怪的acaacg并搜索大小为2的所有重复的子串,我将得到1的计数和0,3的起始位置。然后你可以输入字符串[0:2]和字符串[3:5]来验证它们确实匹配,结果是“ac”。

如果有人有兴趣了解Burrows-Wheeler,维基百科上的搜索会产生非常有用的结果。这是斯坦福大学的另一个来源,也很好地解释了这一点。 http://www.stanford.edu/class/cs262/notes/lecture5.pdf

现在,我在这方面没有提到一些问题。首先,我使用n ^ 2空间来创建BW变换。此外,我正在创建一个后缀数组,对其进行排序,然后将其替换为数字,以便创建可能占用一些空间。但是,最后我只是存储了occ矩阵,结束列和单词本身。

尽管存在RAM问题,因为字符串大于4 ^ 7(使用字符串大小为40,000但没有更大......),我会称之为成功,就像星期一之前一样,我唯一的新方法是在python中做的是让它打印我的名字和你好世界。

#  generate random string of DNA
def get_string(length):
    string=""
    for i in range(length):
        string += random.choice("ATGC")
    return string

#  Make the BW transform from the generated string  
def make_bwt(word):
    word = word + '$'
    return ''.join([x[-1] for x in
        sorted([word[i:] + word[:i] for i in range(len(word))])])
#  Make the occurrence matrix from the transform        
def make_occ(bwt):
    letters=set(bwt)
    occ={}
    for letter in letters:
        c=0
        occ[letter]=[]
        for i in range(len(bwt)):
            if bwt[i]==letter:
            c+=1
            occ[letter].append(c)
    return occ

#  Get the initial starting locations for the Pos(x) values 
def get_starts(word):
    list={}
    word=word+"$"
    for letter in set(word):
        list[letter]=len([i for i in word if i < letter])
    return list

#  Single range finder for the BWT.  This produces a first and last position for one read.  
def get_range(read,occ,pos):
    read=read[::-1]
    firstletter=read[0]
    newread=read[1:len(read)]
    readL=len(read)
    F0=pos[firstletter]
    L0=pos[firstletter]+occ[firstletter][-1]-1

    F1=F0
    L1=L0
    for letter in newread:
        F1=pos[letter]+occ[letter][F1-1]
        L1=pos[letter]+occ[letter][L1] -1
    return F1,L1

#  Iterate the single read finder over the entire string to search for duplicates   
def get_range_large(readlength,occ,pos,bwt):
    output=[]
    for i in range(0,len(bwt)-readlength):
        output.append(get_range(word[i:(i+readlength)],occ,pos))
    return output

#  Create suffix array to use later 
def get_suf_array(word):
    suffix_names=[word[i:] for i in range(len(word))]   
    suffix_position=range(0,len(word))                  
    output=zip(suffix_names,suffix_position)
    output.sort()
    output2=[]
    for i in range(len(output)):                        
        output2.append(output[i][1])
    return output2

#  Remove single hits that were a result of using the substrings to scan the large string   
def keep_dupes(bwtrange):
    mylist=[]
    for i in range(0,len(bwtrange)):
        if bwtrange[i][1]!=bwtrange[i][0]:
            mylist.append(tuple(bwtrange[i]))
    newset=set(mylist)
    newlist=list(newset)
    newlist.sort()
    return newlist

#  Count the duplicate entries
def count_dupes(hits):
    c=0
    for i in range(0,len(hits)):
        sum=hits[i][1]-hits[i][0]
        if sum > 0:
            c=c+sum
        else:
            c
    return c

#  Get the coordinates from BWT and use the suffix array to map them back to their original indices 
def get_coord(hits):
    mylist=[]
    for element in hits:
        mylist.append(sa[element[0]-1:element[1]])
    return mylist

#  Use the coordinates to get the actual strings that are duplicated
def get_dupstrings(coord,readlength):
    output=[]
    for element in coord:
        temp=[]
        for i in range(0,len(element)):         
            string=word[element[i]:(element[i]+readlength)]
            temp.append(string)
        output.append(temp) 
    return output

#  Merge the strings and the coordinates together for one big list. 
def together(dupstrings,coord):
    output=[]
    for i in range(0,len(coord)):
        merge=dupstrings[i]+coord[i]
        output.append(merge)
    return output

Now run the commands as follows
import random  #  This is needed to generate a random string
readlength=12 #  pick read length
word=get_string(4**7) # make random word
bwt=make_bwt(word) # make bwt transform from word
occ=make_occ(bwt)  #  make occurrence matrix  
pos=get_starts(word)  #  gets start positions of sorted first row       
bwtrange=get_range_large(readlength,occ,pos,bwt) #  Runs the get_range function over all substrings in a string.    
sa=get_suf_array(word)  #  This function builds a suffix array and numbers it.  
hits=keep_dupes(bwtrange)   #  Pulls out the number of entries in the bwt results that have more than one hit.
dupes=count_dupes(hits) #  counts hits
coord=get_coord(hits)  #  This part attempts to pull out the coordinates of the hits.  
dupstrings=get_dupstrings(coord,readlength)  #  pulls out all the duplicated strings
strings_coord=together(dupstrings,coord)    #  puts coordinates and strings in one file for ease of viewing.
print dupes
print strings_coord