我有以下代码读出与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) ````
你只追加,当你看到一个新的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文件包含在这种格式的数据:
>ID1
seq_1
>ID2
seq_2
...
根据你的代码,如果你的行包含一个>
才把你尝试添加的顺序。这意味着,要添加的顺序为ID_1当你迭代的ID_2。
要解决这个问题,你可以这样做:
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] == ">"
)后直接来的事实。