为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

肥皂起泡泡 2021-11-02 16:10:17
我有以下代码读取包含 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) ````
查看完整描述

2 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

只有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)


查看完整回答
反对 回复 2021-11-02
?
郎朗坤

TA贡献1921条经验 获得超9个赞

由于 FASTA 文件包含以下格式的数据:


>ID1

seq_1

>ID2

seq_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] == ">")。


查看完整回答
反对 回复 2021-11-02
  • 2 回答
  • 0 关注
  • 316 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号