如何在 python 中将文本中每个句子的开头大写?
在 Python 中,你可以使用字符串方法来将文本中每个句子的开头大写。通常,句子的定义是以句号(.)、感叹号(!)或问号(?)结尾,接着是一个空格或换行符。以下是一个实现该功能的示例:
.
!
?
import re def capitalize_sentences(text: str) -> str: # 使用正则表达式找到每个句子的开头并将其大写 return re.sub(r'([.!?]\s*)(\w)', lambda match: match.group(1) + match.group(2).upper(), text) text = "this is the first sentence. this is the second sentence! and here's the third one?" result = capitalize_sentences(text) print(result)
This is the first sentence. This is the second sentence! And here's the third one?
re.sub(r'([.!?]\s*)(\w)', ...)
lambda match: match.group(1) + match.group(2).upper()
这种方法比较强大,可以处理不同类型的句子分隔符和空格。
如果你的文本格式比较简单(没有复杂的标点符号),你也可以使用字符串方法来逐句处理:
def capitalize_sentences_simple(text: str) -> str: sentences = text.split('. ') # 只考虑句号后的空格作为分隔 sentences = [sentence.capitalize() for sentence in sentences] return '. '.join(sentences) text = "this is the first sentence. this is the second sentence. here's the third one." result = capitalize_sentences_simple(text) print(result)
This is the first sentence. This is the second sentence. Here's the third one.
这种方法适用于简单文本,假设每个句子都以句号、感叹号或问号后跟一个空格开始。
两种方法都可以根据你的需要进行调整,选择最合适的一种。