从SeqIO.index生成的字典中删除一项

2024-04-29 19:22:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.6.6,我试图删除fastq中与file1中的读操作重叠的{}读操作。下面是我要实现的代码:

ref_reads = SeqIO.index("file1.fastq", "fastq")
spk_reads = SeqIO.index("file2.fastq", "fastq")

for spk in spk_reads:
    if spk in ref_reads:
    del ref_reads[spk]

但是,我得到了与使用del有关的错误:

AttributeError:\u IndexedSeqFileDict实例没有属性'\\'delitem\'

有没有可能用目前的提法删除一个项目?如何从使用SeqIO.index()生成的词典中删除项目?在

我还尝试了以下方法:

^{pr2}$

Tags: 项目代码inrefforindexif错误
1条回答
网友
1楼 · 发布于 2024-04-29 19:22:58

在序号索引()不返回真正的字典,但a dictionary like object, giving the SeqRecord objects as values

Note that this pseudo dictionary will not support all the methods of a true Python dictionary, for example values() is not defined since this would require loading all of the records into memory at once.

这个类似字典的对象是一个^{}实例。docstring提到:

Note that this dictionary is essentially read only. You cannot add or change values, pop values, nor clear the dictionary.

因此,您需要使用SeqIO.parse()SeqIO.to_dict()将fastq文件转换为内存中的Python字典:

from Bio import SeqIO

ref_reads = SeqIO.parse("file1.fastq", "fastq")
spk_reads = SeqIO.parse("file1.fastq", "fastq")

ref_reads_dict = SeqIO.to_dict(ref_reads)

for spk in spk_reads:
    if spk.id in ref_reads_dict:
        del ref_reads_dict[spk.id]

如果文件太大,无法使用SeqIO.parse(),那么我将执行以下操作:

^{pr2}$

编辑,回复您的评论:

how can I again solve the original problem of deleting items from SeqIO.index("file1.fastq", "fastq")?

正如我上面所说,SeqIO.index("file1.fastq", "fastq")返回一个只读的_IndexedSeqFileDict对象。因此,您不可以按设计从中删除项目。在

下面更新的代码展示了如何创建一个新的fastq文件,其中删除了重叠的读取。在

如果您真的想要一个新的SeqIO.index()对象,那么您可以用SeqIO.index()再次读入这个文件。在

from Bio import SeqIO

ref_reads = SeqIO.index("file1.fastq", "fastq")
spk_reads = SeqIO.index("file2.fastq", "fastq")

ref_keys = set(ref_reads.keys())  
spk_keys = set(spk_reads.keys())

unique_ref_keys = ref_keys - spk_keys

# conserve memory by using a generator expression
unique_ref_records = (ref_reads[key] for key in unique_ref_keys)

# output new file with overlapping reads removed
with open(fname_out, "w") as output_handle:
    SeqIO.write(unique_ref_records , output_handle, "fastq")

# optionally, create a new SeqIO.index() object 
unique_ref_reads = SeqIO.index(fname_out, "fastq")

相关问题 更多 >