I'm trying to join a set of sentences contained in a list
. I have a function which determines whether a sentence in worth saving. However, in order to keep the context of the sentence I need to also keep the sentence before and after it. In the edge cases, where its either the first or last sentence then, I'll just keep the sentence and its only neighbor.
An example is best:
ex_paragraph = ['The quick brown fox jumps over the fence.',
'Where there is another red fox.',
'They run off together.',
'They live hapily ever after.']
t1 = lambda x: x.startswith('Where')
t2 = lambda x: x'startswith('The ')
The result for t1 should be:
['The quick brown fox jumps over the fence. Where there is another red fox. They run off together.']
The result for t2 should be:
['The quick brown fox jumps over the fence. Where there is another red fox.']
My solution is:
def YieldContext(sent_list, cont_fun):
def JoinSent(sent_list, ind):
if ind == 0:
return sent_list[ind]+sent_list[ind+1]
elif ind == len(sent_list)-1:
return sent_list[ind-1]+sent_list[ind]
else:
return ' '.join(sent_list[ind-1:ind+1])
for sent, sentnum in izip(sent_list, count(0)):
if cont_fun(sent):
yield JoinSent(sent_list, sent_num)
Does anyone know a "cleaner" or more pythonic way to do something like this. The if-elif-else
seems a little forced.
Thanks,
Will
PS. I'm obviously doing this with a more complicated "context-function" but this is just for a simple example.