在 python 中尝试读取 .fasta 文件时出现错误
Im getting error while tring to read .fasta file in python
我正在尝试将 .fasta 文件作为字典读取并提取文件中的 header 和序列 separately.there 是几个 header 和序列。
下面是一个例子。
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'
使用yield
关键字意味着当你调用函数read_fasta
时,函数不会被执行。相反,会返回一个生成器,您必须迭代此生成器以获取函数生成的元素。
具体来说,将 dict = read_fasta(fasta)
替换为 dict = read_fasta(*fasta)
应该可以完成这项工作(* 是解包的运算符)。
正如 Iguananaut 已经提到的,Bipython 可以帮助您。 (需要安装 biopython 包)
参见 Biopython "sequence file to dictionary"
from Bio import SeqIO
fasta= "sample.prot.fasta"
seq_record_dict = SeqIO.to_dict(SeqIO.parse(fasta, "fasta"))
我正在尝试将 .fasta 文件作为字典读取并提取文件中的 header 和序列 separately.there 是几个 header 和序列。 下面是一个例子。
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'
使用yield
关键字意味着当你调用函数read_fasta
时,函数不会被执行。相反,会返回一个生成器,您必须迭代此生成器以获取函数生成的元素。
具体来说,将 dict = read_fasta(fasta)
替换为 dict = read_fasta(*fasta)
应该可以完成这项工作(* 是解包的运算符)。
正如 Iguananaut 已经提到的,Bipython 可以帮助您。 (需要安装 biopython 包) 参见 Biopython "sequence file to dictionary"
from Bio import SeqIO
fasta= "sample.prot.fasta"
seq_record_dict = SeqIO.to_dict(SeqIO.parse(fasta, "fasta"))