For extracting the first instance, your code does work but has some unnecessary code.
Simply append i
, not i.split('.')[0]
. Your i
is already splitted.
for j in words:
for i in text.split('.'):
if j in i:
lst.append(i)
break
Now for extracting n sentences,
for j in words:
for index, i in enumerate(text.split('.')):
if j in i:
if j == "dog" or j == "cat":
lst.append('.'.join(text.split('.')[index:index+n]))
else:
lst.append(i)
break
Here using enumerate, we track the index of the sentences. If we encounter a sentence with dog or cat, instead of appending we add the sublist with length n.
CLICK HERE to find out more related problems solutions.