Capitalization of each sentence in a string in Python 3

后端 未结 5 1132
-上瘾入骨i
-上瘾入骨i 2021-01-22 10:25

This should be easy but somehow I\'m not quite getting it.

My assignment is:

Write a function sentenceCapitalizer that has one parameter of type

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 10:29

    This does the job. Since it extracts all sentences including their trailing whitespace, this also works if you have multiple paragraphs, where there are line breaks between sentences.

    import re
    
    def sentence_case(text):
        # Split into sentences. Therefore, find all text that ends
        # with punctuation followed by white space or end of string.
        sentences = re.findall('[^.!?]+[.!?](?:\s|\Z)', text)
    
        # Capitalize the first letter of each sentence
        sentences = [x[0].upper() + x[1:] for x in sentences]
    
        # Combine sentences
        return ''.join(sentences)
    

    Here is a working example.

提交回复
热议问题