让我们假设我有以下段落:
"This is the first sentence. This is the second sentence? This is the third
sentence!"
我需要创建一个函数,它只返回给定字符数下的句子数。如果小于一个句子,它将返回第一个句子的所有字符。
例如:
>>> reduce_paragraph(100)
"This is the first sentence. This is the second sentence? This is the third
sentence!"
>>> reduce_paragraph(80)
"This is the first sentence. This is the second sentence?"
>>> reduce_paragraph(50)
"This is the first sentence."
>>> reduce_paragraph(5)
"This "
我从这样的事情开始,但我似乎无法弄清楚如何完成它:
endsentence = ".?!"
sentences = itertools.groupby(text, lambda x: any(x.endswith(punct) for punct in endsentence))
for number,(truth, sentence) in enumerate(sentences):
if truth:
first_sentence = previous+''.join(sentence).replace('\n',' ')
previous = ''.join(sentence)