Python在上下文后打印行

问题描述 投票:1回答:2

如何在我对使用python感兴趣的上下文后打印两行。

Example.fastq

@read1
AAAGGCTGTACTTCGTTCCAGTTG
+
'(''%$'))%**)2+'.(&&'/5-
@read2
CTGAGTTGAGTTAGTGTTGACTC
+
)(+-0-2145=588..,(1-,12

我可以使用...找到感兴趣的上下文

fastq = open(Example.fastq, "r")

IDs = [read1]

with fastq as fq:
    for line in fq:
        if any(string in line for string in IDs):

现在我找到了read1,我想打印出read1的以下行。在bash中我可能会使用像grep -A这样的东西。所需的输出行如下所示。

+
'(''%$'))%**)2+'.(&&'/5-

但在python中我似乎无法找到一个等效的工具。也许“islice”可能有效,但我不知道如何从比赛的位置开始islice。

with fastq as fq:
    for line in fq:
        if any(string in line for string in IDs):
            print(list(islice(fq,3,4)))
python grep bioinformatics fasta fastq
2个回答
3
投票

您可以使用next()来推进迭代器(包括文件):

print(next(fq))
print(next(fq))

这会消耗这些线,因此for循环将继续使用@read2

如果你不想要AAA...线,你也可以用next(fq)消费它。在全:

fastq = open(Example.fastq, "r")

IDs = [read1]

with fastq as fq:
    for line in fq:
        if any(string in line for string in IDs):
            next(fq)  # skip AAA line
            print(next(fq).strip())  # strip off the extra newlines
            print(next(fq).strip())

这使

+
'(''%$'))%**)2+'.(&&'/5-

1
投票

如果您正在处理FASTQ文件,最好使用像BioPython这样的生物信息库而不是滚动自己的解析器。

要获得您要求的确切结果,您可以:

from Bio.SeqIO.QualityIO import FastqGeneralIterator

IDs = ['read1']

with open('Example.fastq') as in_handle:
    for title, seq, qual in FastqGeneralIterator(in_handle):
        # The ID is the first word in the title line (after the @ sign):
        if title.split(None, 1)[0] in IDs:
            # Line 3 is always a '+', optionally followed by the same sequence identifier again.
            print('+') 
            print(qual)

但是你自己对质量价值观的影响不大。您的下一步几乎肯定是将其转换为Phred quality scores。但这是出了名的复杂because there are at least three different and incompatible variants of the FASTQ file format。 BioPython为您处理所有边缘情况,以便您可以:

from Bio.SeqIO import parse

IDs = ['read1']

with open('Example.fastq') as in_handle:
    for record in parse(in_handle, 'fastq'):
        if record.id in IDs:
            print(record.letter_annotations["phred_quality"])
© www.soinside.com 2019 - 2024. All rights reserved.