简体   繁体   English

如何从文本中检索“n”行?

[英]How to retrieve "n" lines from a text?

I am working with a FastQ file which is a text file with different elements in every 4 lines.我正在处理一个 FastQ 文件,它是一个文本文件,每 4 行包含不同的元素。 I am trying to search for a certain string in a line and retrieve that line with the following three lines.我试图在一行中搜索某个字符串并使用以下三行检索该行。 But I am not sure how to do that.但我不知道该怎么做。 So far, I am only able to retrieve the target line, but not the following three.到目前为止,我只能检索目标行,而不能检索以下三个。 Supposing that my target line has a "XXXX" as part of the string, a fragment of my code is as follows:假设我的目标行有一个“XXXX”作为字符串的一部分,我的代码片段如下:

with open (x, 'rt') as myfile:   
    for line in myfile:

        if re.findall ('.+XXXX.+', line):
            target.write (line)
            count_target = count_target + 1

        else:
            leftover.write (line)
            count_left = count_left + 1

How could I improve my code to get the four consecutive lines everytime it founds "XXXX"?我如何改进我的代码以在每次找到“XXXX”时获得连续四行?

Once you found your line, call next(myfile) 3 times:找到您的线路后,调用next(myfile) 3 次:

with open (x, 'rt') as myfile:   
    for line in myfile:

        if re.findall ('.+XXXX.+', line):
            target.write (line)
            for i in range(3):
                target.write(next(myfile))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM