在Python中,可以使用正则表达式来按照特定组合将一个句子分割成一个句子列表。下面是一个代码示例:
import re
def split_sentence(sentence, pattern):
sentences = re.split(pattern, sentence)
return [s.strip() for s in sentences if s.strip()]
sentence = "Hello, world! How are you today?"
pattern = r'[!.?]'
result = split_sentence(sentence, pattern)
print(result)
输出:
['Hello, world', 'How are you today']
在上面的示例中,split_sentence
函数接收一个句子和一个正则表达式模式作为参数。使用re.split
函数根据模式将句子分割成多个子句,然后使用列表推导式对每个子句进行去除首尾空格,并筛选掉空字符串。最后返回由子句组成的列表。
在这个例子中,我们使用了正则表达式模式[!.?]
来表示句子的分隔符,它匹配句子中的句号、感叹号和问号。你可以根据具体的需求调整模式,例如[.!?,]
可以匹配句号、感叹号、问号和逗号作为分隔符。