【发布时间】:2017-09-21 10:48:11
【问题描述】:
最近的一个项目让我需要将传入的短语(作为字符串)拆分为它们的组成句子。例如,这个字符串:
"Your mother was a hamster, and your father smelt of elderberries! Now go away, or I shall taunt you a second time. You know what, never mind. This entire sentence is far too silly. Wouldn't you agree? I think it is."
需要变成由以下元素组成的列表:
["Your mother was a hamster, and your father smelt of elderberries",
"Now go away, or I shall taunt you a second time",
"You know what, never mind",
"This entire sentence is far too silly",
"Wouldn't you agree",
"I think it is"]
对于此函数,“句子”是一个以!、? 或. 结尾的字符串。请注意,如上所示,应从输出中删除标点符号。
我有一个工作版本,但它很丑,前导和尾随空格,我不禁想到有更好的方法:
from functools import reduce
def split_sentences(st):
if type(st) is not str:
raise TypeError("Cannot split non-strings")
sl = st.split('.')
sl = [s.split('?') for s in sl]
sl = reduce(lambda x, y: x+y, sl) #Flatten the list
sl = [s.split('!') for s in sl]
return reduce(lambda x, y: x+y, sl)
【问题讨论】: