Welcome, guest | Sign In | My Account | Store | Cart

Recapitalizes text, placing caps after end-of-sentence punctuation. Turning "hello world. how are you?" to "Hello world. How are you?"

Python, 18 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# This is derived from code provided by the Django Project. 
# Original code is licensed under the terms of the BSD license.
# See https://github.com/django/django/blob/master/LICENSE for full original license terms
import re

re_caps = re.compile(r'(?:^|(?<=[\.\?\!]))(^\s*|\s+)([a-z])')
def recapitalize(text):
     """Recapitalizes text, placing caps after end-of-sentence punctuation."""
     text = text.lower()
     text = re_caps.sub(lambda x: x.group(1) + x.group(2).upper(), text)
     return text

if __name__ == "__main__":
    print(recapitalize("first sentence. SECOND SENTENCE? tHiRd SeNtEnCe, "
                       "and it is still third sentence! FOURTH sentence."))
    print(recapitalize("\r\nfirst sentence.  second.sentence?\n"
                       "tHiRd;SeNtEnCe, and it is still third sentence!"
                       "\tFOURTH sentence."))

Originally the code was from django.utils.text.recapitalize, but it was removed in https://github.com/django/django/commit/b4a11f2720fbbb47f7c03a5a00b3cfb334266a92

So I decided to save it here. But I modified it because originally the function is too dumb: https://code.djangoproject.com/ticket/21651

Created by sky kok on Wed, 25 Dec 2013 (BSD)
Python recipes (4591)
sky kok's recipes (1)

Required Modules

Other Information and Tasks