我在如何使用嵌入在类中的函数在python中实现代码时遇到了困难。在编写代码之后,大多数示例都在线结束,但是没有向您展示(可能因为它太简单了)如何在输入示例文件“testfile.txt”上运行它。所以假设下面的代码是正确的(如果有效等等对我来说无关紧要),我将如何运行它并在“testfile.txt”上检索标题和序列变量?
这是从以下代码借来的代码: https://www.biostars.org/p/710/
class Dna:
''' Object representing a FASTA record. '''
def __init__(self, header, sequence):
self.head = header
self.seq = sequence
def __repr__(self):
return '[HTML]' % (self.head)
def __str__(self, separator=''):
return '>%s\n%s' % (self.head, separator.join(self.seq))
def __len__(self):
return len(''.join(self.seq))
@property
def sequence(self, separator=''):
return separator.join(self.seq)
class Fasta:
''' A FASTA iterator/generates DNA objects. '''
def __init__(self, handle):
self.handle = handle
def __repr__(self):
return '[HTML]' % handle
def __iter__(self):
header, sequence = '', []
for line in self.handle:
if line[0] == '>':
if sequence: yield Dna(header, sequence)
header = line[1:-1]
sequence = []
else:
sequence.append(line.strip())
yield Dna(header, sequence)
答案 0 :(得分:1)
Fasta
实例采用文件对象:
with open('testfile.txt') as infh:
fasta = Fasta(infh)
for dna in fasta:
print(dna.head)
print(dna.sequence)
它实际上在帖子中告诉你:
您执行
fasta = Fasta(handle)
然后for record in fasta
以生成Dna对象