我有一个很大的文件,里面有很多FASTA序列。其中一些需要重命名-我正在尝试将FASTA序列ID替换为它们的更新版本。我将信息存储在字典中,以使旧ID为键,而新ID为值。无论我做什么,我似乎都无法替换ID或正确写入新的fasta文件。我正在使用SeqIO读取我的fasta文件。这是我的一些代码:
这将导致记录ID的浅层替换,因为它们可以在此处正确打印,但实际上在文件本身中并未更改:
rename_fastas = {'446_was_445_cDNA_v01VT':'446_cDNA_v01VT', '446_was_445_cDNA_v03VT': '446_cDNA_v03VT',
'428PBMC_2_V3': '428_PBMC_2_V3', '428PBMC_3_V3': '428_PBMC_3_V3', '428PBMC_4_V3': '428_PBMC_4_V3', '428PBMC_5_V3': '428_PBMC_5_V3'}
with open('fasta.fsa') as f:
for seq_record in SeqIO.parse(f, 'fasta'):
for k,v in rename_fastas.items():
if seq_record.id == k:
seq_record.id = seq_record.description = seq_record.id.replace(k,v)
print(seq_record.id)
这使我无法在新文件中添加太多条目:
with open('fasta.fsa') as original,
open('fasta2.fsa', 'w') as corrected:
records = SeqIO.parse(original, 'fasta')
for record in records:
for k, v in rename_fastas.items():
if record.id == k:
record.id = record.description.replace(k, v)
else:
record.id = record.id
SeqIO.write(record, corrected, 'fasta')
这也不起作用,我不确定为什么:
with open('fasta.fsa') as f:
for seq_record in SeqIO.parse(f, 'fasta'):
seq_record.id = seq_record.description = seq_record.id.replace('428PBMC','428_PBMC')
seq_record.id = seq_record.description = seq_record.id.replace('446_was_445','446')
yield seq_record
任何帮助将不胜感激!
答案 0 :(得分:2)
尝试一个:
rename_fastas = {'446_was_445_cDNA_v01VT':'446_cDNA_v01VT', '446_was_445_cDNA_v03VT': '446_cDNA_v03VT', '428PBMC_2_V3': '428_PBMC_2_V3', '428PBMC_3_V3': '428_PBMC_3_V3', '428PBMC_4_V3': '428_PBMC_4_V3', '428PBMC_5_V3': '428_PBMC_5_V3'}
with open('fasta.fsa') as original, open('fasta2.fsa', 'w') as corrected:
for seq_record in SeqIO.parse(original, 'fasta'):
if seq_record.id in rename_fastas:
seq_record.id = seq_record.description = rename_fastas[seq_record.id]
SeqIO.write(seq_record, corrected, 'fasta')
您打开文件进行输入和输出。您有一个具有适当键的字典,因此无需每次都遍历它,只需要求该字典完成其工作并通过其键进行访问即可。如果字典中存在键,则用ID的整个值替换字典中的值。最后,将更正的记录写入输出文件。