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)

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] == ">")。
添加回答
舉報