尝试读取python中的.fasta文件时出错

问题描述 投票:0回答:1

im试图将.fasta文件作为字典读取,并分别提取标题和序列。文件中有多个标题和序列。下面的例子。

header= CMP12
sequence=agcgtmmnngucnncttsckkld

但是当我尝试使用read_f函数读取fasta文件并使用print(dict.keys())对其进行测试时,我得到一个空列表。

def read_f(fasta):
    '''Read a file from a FASTA format'''

    dictionary = {}
    with open(fasta) as file:
        text = file.readlines()
        print(text)

    name=''
    seq= ''
    #Create blocks of fasta text for each sequence, EXCEPT the last one
    for line in text:
        if line[0]=='>':
            dictionary[name] = seq
            name=line[1:].strip()
            seq=''

        else: seq = seq + line.strip()
    yield name,seq


fasta= ("sample.prot.fasta")
dict = read_f(fasta)

print(dict.keys())

这是我得到的错误:

'generator' object has no attribute 'keys'
python fasta
1个回答
2
投票

使用yield关键字表示您在调用函数read_fasta时未执行该函数。相反,将返回一个生成器,并且您必须迭代此生成器以获取函数产生的元素。具体来说,用dict = read_fasta(fasta)代替dict = read_fasta(*fasta)应该可以完成这项工作(*是开箱的操作员。)>

© www.soinside.com 2019 - 2024. All rights reserved.