0

What is the best way to solve my problem?

I have a file that contains string lines. I want to analyze it. So in my approach I need to take first N lines, do something with them, than instead 1-st line I need to take N+1 line and analyze this block, than instead 2-nd line - N+2 line and so on to the end of the file.

st_1
st_2
st_3
...
st_LAST

First block:

[st_1, st_2, ... , st_N]

Second block:

[st_2, st_3, ... , st_N, st_N+1]

Last Block:

[st_LAST-N, st_LAST-N+1, ... , st_LAST]
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Possible duplicate of [Rolling or sliding window iterator?](https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator) – tripleee Feb 05 '19 at 12:22

2 Answers2

0

Let's consider you've assigned the text of the file to a variable (s). Next, you can split it by lines. Loop through the range of length and use it to create slices and loop them though.

s='some text1\nsome text2\nsome text3\nsome text4\nsome text5\nsome text6\n'
n_block = 3 # size of the block you want to split
list_s=s.split('\n')
for i in range(len(list_s)):
    block = i + n_block if i + n_block < len(list_s)-1 else len(list_s)-1
    for y in list_s[i:block]:
        #...
        #do something
        #...
Tiago Gomes
  • 357
  • 4
  • 12
Igor Dragushhak
  • 567
  • 1
  • 3
  • 14
0

This should work:

filename = "your_file.txt"
with open(filename,'r') as f:
    lines = f.readlines()

N = 5# size of block

for i in range(len(lines)-N+1):
    print(lines[i:i+block_size])