Вы можете сжать sentences
с одним смещением, используя zip_longest
из itertools.Это позволит вам выполнить проверку, выполнить конкатенацию при необходимости и пропустить следующую итерацию, если это не так.
from itertools import zip_longest
sentences2 = []
skip = False
for s1, s2 in zip_longest(sentences, sentences[1:]):
if skip:
skip = False
continue
if s1.split()[-1].lower() in exceptions:
sentences2.append(f'{s1} {s2}')
skip = True
else:
sentences2.append(s1)
sentences2
# returns:
['this is first', 'this is one this is three', 'this is four this is five', 'this is six']
Редактировать:
Вам необходимо обработать случай объединения нескольких предложений встрока.В этой ситуации вы можете использовать флаг, чтобы отслеживать, следует ли вам присоединиться к следующему предложению или нет.Это немного сложнее, но здесь это так:
sentences2 = []
join_next = False
candidate = None
for s in sentences:
if join_next:
candidate += (' ' + s)
join_next = False
if candidate is None:
candidate = s
if s.split()[-1].lower() in exceptions:
join_next = True
continue
else:
sentences2.append(candidate)
candidate = None
sentences2
# returns:
['this is first',
'this is one this is three',
'this is four this is five',
'this is six']
Вот пример, который добавляет дополнительное предложение, которое требует объединения в цепочку.
sentences3 = ['this is first', 'this is one', 'extra here four',
'this is three', 'this is four', 'this is five', 'this is six']
sentences4 = []
join_next = False
candidate = None
for s in sentences3:
if join_next:
candidate += (' ' + s)
join_next = False
if candidate is None:
candidate = s
if s.split()[-1].lower() in exceptions:
join_next = True
continue
else:
sentences4.append(candidate)
candidate = None
sentences4
# returns:
['this is first',
'this is one extra here four this is three',
'this is four this is five',
'this is six']