How to capitalize the first letter of every sentence?

user3307366 picture user3307366 · Apr 2, 2014 · Viewed 29.5k times · Source

I'm trying to write a program that capitalizes the first letter of each sentence. This is what I have so far, but I cannot figure out how to add back the period in between sentences. For example, if I input:

hello. goodbye

the output is

Hello Goodbye

and the period has disappeared.

string=input('Enter a sentence/sentences please:')
sentence=string.split('.')
for i in sentence:
    print(i.capitalize(),end='')

Answer

jfs picture jfs · Apr 2, 2014

You could use nltk for sentence segmentation:

#!/usr/bin/env python3
import textwrap
from pprint import pprint
import nltk.data # $ pip install http://www.nltk.org/nltk3-alpha/nltk-3.0a3.tar.gz
# python -c "import nltk; nltk.download('punkt')"

sent_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
text = input('Enter a sentence/sentences please:')
print("\n" + textwrap.fill(text))
sentences = sent_tokenizer.tokenize(text)
sentences = [sent.capitalize() for sent in sentences]
pprint(sentences)

Output

Enter a sentence/sentences please:
a period might occur inside a sentence e.g., see! and the sentence may
end without the dot!
['A period might occur inside a sentence e.g., see!',
 'And the sentence may end without the dot!']