Once i enter in this loop, how could i print not only the current line, but the next 3 lines after the current line ?
for line in work01:
if any(word in line for word in inc_list):
print(line)
If you don't want overlapping occurrences of the pattern, you could do
from itertools import islice
items = iter(work01) # <- we need an iterator, not just an iterable
for line in items:
if any(word in line for word in inc_list):
print(line)
for subsequent in islice(items, None, 3):
print(subsequent)
Maybe get a slice of the list if: any(word in line for word in inc_list) = True?
from random import choice
words = ['ant', 'bee', 'cauliflower', 'cow', 'bean']
work01_list = [f'Line {i} stuff line {choice(words)}.\n' for i in range(1,11)]
inc_list = ['bean', 'cauliflower']
for i in range(len(work01_list)):
line = work01_list[i]
if any(word in line for word in inc_list):
list_slice = work01_list[i:i+4]
for w in inc_list:
if w in list_slice[0]:
word = w
for j in list_slice:
print(f'word = {word}, {j}')
print('End of slice ... \n')
# put break here to stop after the first 4 lines
#break
Gribouillis said something about not overlapping. You could do that like this:
work01_gen = (f'Line {i} stuff line {choice(words)}.\n' for i in range(1,31))
for w in work01_gen:
try:
if any(word in w for word in inc_list):
print('Found a wanted word, now printing the next 3 lines ... ')
for i in range(3):
print(next(work01_gen))
except StopIteration:
print('Run out of generator items!')
You can use a counter to keep track of the lines. Modify your loop to print the current line and then the next three lines by using the
islice
function from the
itertools
module. Here is an example:
[inline]from itertools import islice
for i, line in enumerate(work01):
if any(word in line for word in inc_list):
print(line)
for next_line in islice(work01, i+1, i+4):
print(next_line)
[/inline]
This will print the matched line and the following three lines.