Skip to main content
 首页 » 编程设计

python之通过结尾字符拆分句子

2025年05月04日1252php

最近的一个项目让我需要将传入的短语(作为字符串)拆分成它们的组成句子。例如,这个字符串:

“你妈妈是一只仓鼠,你爸爸闻起来有接骨木果的味道!现在走开,否则我会 mock 你第二次。你知道吗,没关系。这整句话太愚蠢了。不会'你不同意吗?我想是的。”

需要变成一个由以下元素组成的列表:

["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) 

请您参考如下方法:

使用 re.split 来指定匹配任何句末字符(以及任何后续空格)的正则表达式。

def split_sentences(st): 
    sentences = re.split(r'[.?!]\s*', st) 
    if sentences[-1]: 
        return sentences 
    else: 
        return sentences[:-1]