在fasta文件中更改反向序列的方向不起作用

时间:2018-08-01 11:03:50

标签: python python-2.7 pysam

我正在尝试使反向序列在文件中正确定向。这是代码:

import os
import sys import pysam
from Bio import SeqIO, Seq, SeqRecord

def main(in_file):
    out_file = "%s.fa" % os.path.splitext(in_file)[0]
    with open(out_file, "w") as out_handle:
        # Write records from the BAM file one at a time to the output file.
        # Works lazily as BAM sequences are read so will handle large files.
        SeqIO.write(bam_to_rec(in_file), out_handle, "fasta")

def bam_to_rec(in_file):
    """Generator to convert BAM files into Biopython SeqRecords.
    """
bam_file = pysam.Samfile(in_file, "rb")
for read in bam_file:
    seq = Seq.Seq(read.seq)
    if read.is_reverse:
        seq = seq.reverse_complement()
    rec = SeqRecord.SeqRecord(seq, read.qname, "", "")
    yield rec

if __name__ == "__main__":
    main(*sys.argv[1:])`

当我打印出反向序列时,代码起作用。但是在文件中时,它以相反的顺序打印出来。谁能帮助我找出问题所在? 这是我的档案的链接: https://www.dropbox.com/sh/68ui8l7nh5fxatm/AABUr82l01qT1nL8I_XgJaeTa?dl=0

1 个答案:

答案 0 :(得分:1)

请注意,丑陋的计数器仅可打印10000个序列,而不是更多。

比较一个而不需要反转,如果需要则反转 这是几个序列的输出,可以随时对其进行测试,我想您的问题是yield会返回一个迭代器,但您并未对其进行迭代,除非我误解了您正在做什么:

原文:

  

SOLEXA-1GA-2:2:93:1281:961#0   GGGTTAGGTTAGGGTTAGGGTTAGGGTTAGGGTTAG

成为:

  

SOLEXA-1GA-2:2:93:1281:961#0   CTAACCCTAACCCTAACCCTAACCCTAACCTAACCC

如果不是相反的话:

原文:

  

SOLEXA-1GA-2:2:12:96:1547#0   ACACACAAACACACACACACACACACACACACACCCCCCC

成为:

  

SOLEXA-1GA-2:2:12:96:1547#0   ACACACAAACACACACACACACACACACACACACCCCCCC   这是我的代码:

import os
import sys 
import pysam
from Bio import SeqIO, Seq, SeqRecord

def main(in_file):
    out_file = "%s.fa" % os.path.splitext(in_file)[0]
    with open('test_non_reverse.txt', 'w') as non_reverse:
        with open(out_file, "w") as out_handle:
            # Write records from the BAM file one at a time to the output file.
            # Works lazily as BAM sequences are read so will handle large files.
            i = 0
            for s in bam_to_rec(in_file):
                if i == 10000:
                   break
                i +=1 
                SeqIO.write(s, out_handle, "fasta")
            i = 0
            for s in convert_to_seq(in_file):
                if i == 10000:
                   break
                i +=1

                SeqIO.write(s, non_reverse, 'fasta')

def convert_to_seq(in_file):
    bam_file = pysam.Samfile(in_file, "rb")
    for read in bam_file:
        seq = Seq.Seq(read.seq)
        rec = SeqRecord.SeqRecord(seq, read.qname, "", "")
        yield rec


def bam_to_rec(in_file):
    """Generator to convert BAM files into Biopython SeqRecords.
    """
    bam_file = pysam.Samfile(in_file, "rb")
    for read in bam_file:
        seq = Seq.Seq(read.seq)
        if read.is_reverse:
            seq = seq.reverse_complement()
        rec = SeqRecord.SeqRecord(seq, read.qname, "", "")
        yield rec

if __name__ == "__main__":
    main(*sys.argv[1:])