使用Python编写的ToSentences()函数将文本划分成句子
发布时间:2023-12-17 11:17:05
下面是使用Python编写的ToSentences()函数:
import re
def ToSentences(text):
# 使用正则表达式将文本划分为句子
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', text)
return sentences
# 测试例子
text = "Hello! How are you? I am fine. Thank you for asking. I hope you are doing well. Goodbye!"
sentences = ToSentences(text)
for sentence in sentences:
print(sentence)
输出:
Hello! How are you? I am fine. Thank you for asking. I hope you are doing well. Goodbye!
该函数首先使用正则表达式 r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s' 将文本按照句号(.)或问号(?)后面的空格进行划分。
然后,函数返回划分后的句子列表。
在上面的例子中,我们测试了一个包含了6个句子的文本,并将每个句子都打印出来。
