簡體   English   中英

上下文后的Python打印行

[英]Python print lines after context

我對使用python感興趣的上下文后如何打印兩行。

例子.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)))

您可以使用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-

如果要處理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質量得分 但這非常復雜, 因為FASTQ文件格式至少存在三個不同且不兼容的變體 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"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM