猿问

从 FASTA 文件中提取基因序列?

我有以下代码读取包含 10 个基因序列的 FASTA 文件并将每个序列作为矩阵返回。然而,代码似乎在最后一个序列中丢失了,我想知道为什么?


file=open('/Users/vivianspro/Downloads/rosalind_cons (5).txt', 'r')

line=file.readline()


strings = []

sequence=''

while line:

    #line=line.rstrip('\n')

    line = line.strip() #empty () automatically strips the \n

    if '>' in line:

        if sequence != "":

            strings.append(sequence)

            sequence = ""

        #sequence=line

    else:

        sequence+=line

    line=file.readline()

for s in strings:

    print(s)


Motifs = []

for seq in strings:

    Motifs.append(list(seq))


#make every symbol into an element in the list separated by ,

for s in Motifs:

    print(s) ````


肥皂起泡泡
浏览 318回答 2
2回答

千巷猫影

只有strings当您看到一个新的时才追加到,>但在最后一个序列之后没有。这是一个重构,希望它也更加地道。strings = []sequence=''with open('/Users/vivianspro/Downloads/rosalind_cons (5).txt', 'r') as file:    for line in file:        line = line.rstrip('\n')        if line.startswith('>'):            if sequence != "":                strings.append(sequence)            sequence = ""        else:            sequence+=line    # After the last iteration, append once more if we have something to append    if sequence:        strings.append(sequence)

郎朗坤

由于 FASTA 文件包含以下格式的数据:>ID1seq_1>ID2seq_2...根据您的代码,如果您的行>只包含一个,那么您尝试追加序列。这意味着,当您迭代 ID_2 时,您正在添加 ID_1 的序列。要解决此问题,您可以执行以下操作:for line in file:    line = line.strip()    if '>' in line: # Line 1        line = file.readline().strip()        # print(line)        strings.append(line)上面的示例使用了这样一个事实,即在 FASTA 文件中,序列直接出现在包含>字符的 ID 之后(您可以更改第 1 行,以便它只检查第一个字符, line[0] == ">")。
随时随地看视频慕课网APP

相关分类

Python
我要回答