使用python拼接文本文件的一行



我正在尝试创建遗传签名。我有一个全是DNA序列的文本文件。我想从文本文件中读取每一行。然后将4个碱基加到字典中。示例:样本序列

ATGATATATCTATCAT

我想添加的是ATGA, TGAT, GATA等。添加到一个ID为1的字典中,同时添加4。

所以字典将保存…

Genetic signatures, ID
ATGA,1
TGAT, 2
GATA,3

这是我到目前为止所做的…

import sys  
def main ():
    readingFile = open("signatures.txt", "r")
    my_DNA=""
    DNAseq = {} #creates dictionary 
    for char in readingFile:
        my_DNA = my_DNA+char
    for char in my_DNA:             
        index = 0
        DnaID=1
        seq = my_DNA[index:index+4]         
        if (DNAseq.has_key(seq)): #checks if the key is in the dictionary
            index= index +1
        else :
            DNAseq[seq] = DnaID
            index = index+1
            DnaID= DnaID+1
    readingFile.close()
if __name__ == '__main__':
    main()

下面是我的输出:

ACTC
ACTC
ACTC
ACTC
ACTC
ACTC

这个输出表明它没有遍历字符串中的每个字符…请帮助!

您需要在循环之前移动您的indexDnaID声明,否则它们将在每次循环迭代时被重置:

index = 0
DnaID=1
for char in my_DNA:             
    #... rest of loop here

一旦你做了这个改变,你会得到这样的输出:

ATGA 1
TGAT 2
GATA 3
ATAT 4
TATA 5
ATAT 6
TATC 6
ATCT 7
TCTA 8
CTAT 9
TATC 10
ATCA 10
TCAT 11
CAT 12
AT 13
T 14

为了避免最后3项长度不正确,你可以修改你的循环:

for i in range(len(my_DNA)-3):
    #... rest of loop here

这不会遍历最后3个字符,从而输出:

ATGA 1
TGAT 2
GATA 3
ATAT 4
TATA 5
ATAT 6
TATC 6
ATCT 7
TCTA 8
CTAT 9
TATC 10
ATCA 10
TCAT 11

这应该会给您想要的效果。

from collections import defaultdict
readingFile = open("signatures.txt", "r").read()
DNAseq      = defaultdict(int)
window      = 4
for i in xrange(len(readingFile)):
    current_4mer = readingFile[i:i+window]
    if len(current_4mer) == window:
        DNAseq[current_4mer] += 1
print DNAseq

每次通过从for char in my_DNA:开始的循环将index重置为0。

同时,我认为循环条件应该像while index < len(my_DNA)-4:这样与循环体一致。

你的索引计数器会自动重置,因为它们在for循环中。

我可以提出一些进一步的建议吗?我的解决方案是这样的:
readingFile = open("signatures.txt", "r")
my_DNA=""
DNAseq = {} #creates dictionary 
for line in readingFile:    
    line = line.strip()
    my_DNA = my_DNA + line
ID = 1
index = 0
while True:
    try:
        seq = my_DNA[index:index+4]
        if not seq in my_DNA:
            DNAseq[ID] = my_DNA[index:index+4]
        index += 4
        ID += 1
    except IndexError:
        break
readingFile.close()

但是您想如何处理重复项呢?例如,如果像ATGC这样的序列出现两次?两个都应该添加在不同的ID下,比如{...1:'ATGC', ... 200:'ATGC',...},还是可以省略?

如果我理解正确,你是计算每4个碱基的顺序字符串发生的频率吗?试试这个:

def split_to_4mers(filename):
    dna_dict = {}
    with open(filename, 'r') as f:
        # assuming the first line of the file, only, contains the dna string
        dna_string = f.readline();
        for idx in range(len(dna_string)-3):
            seq = dna_string[idx:idx+4]
            count = dna_dict.get(seq, 0)
            dna_dict[seq] = count+1
    return dna_dict

只包含" atgatatatatcat "的文件的输出:

{'TGAT': 1, 'ATCT': 1, 'ATGA': 1, 'TCAT': 1, 'TATA': 1, 'TATC': 2, 'CTAT': 1, 'ATCA': 1, 'ATAT': 2, 'GATA': 1, 'TCTA': 1}

最新更新