11

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='')
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
user3307366
  • 307
  • 3
  • 6
  • 15

15 Answers15

13

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!']
jfs
  • 399,953
  • 195
  • 994
  • 1,670
7

You could use regular expressions. Define a regex that matches the first word of a sentence:

import re
p = re.compile(r'(?<=[\.\?!]\s)(\w+)')

This regex contains a positive lookbehind assertion (?<=...) which matches either a ., ? or !, followed by a whitespace character \s. This is followed by a group that matches one or more alphanumeric characters \w+. In effect, matching the next word after the end of a sentence.

You can define a function that will capitalise regex match objects, and feed this function to sub():

def cap(match):
    return(match.group().capitalize())

p.sub(cap, 'Your text here. this is fun! yay.')

You might want to do the same for another regex that matches the word at the beginning of a string:

p2 = re.compile(r'^\w+')

Or make the original regex even harder to read, by combining them:

p = re.compile(r'((?<=[\.\?!]\s)(\w+)|(^\w+))')
Marc Maxmeister
  • 4,191
  • 4
  • 40
  • 54
desired login
  • 1,138
  • 8
  • 15
4

You can use,

In [25]: st = "this is first sentence. this is second sentence. and this is third. this is fourth. and so on"

In [26]: '. '.join(list(map(lambda x: x.strip().capitalize(), st.split('.'))))
Out[26]: 'This is first sentence. This is second sentence. And this is third. This is fourth. And so on'

In [27]:
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
3

Maybe something like this:

print('.'.join(i.capitalize() for i in sentence))
Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
  • capitalize() only capitalize the first letter and convert all other words in that sentence in lower case. yes, even nouns too. – Tanmay Bairagi Jul 21 '20 at 15:29
2
x = 'hello. goodbye. and how are you doing.'
print( '. '.join(map(lambda s: s.strip().capitalize(), x.split('.'))))

# Hello. Goodbye. And how are you doing. 
sth
  • 222,467
  • 53
  • 283
  • 367
Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
2

If you want to get only the first letter of a sentence to be capitalised, and do not change the rest of sentence, then you can get the first char, and then convert it to upper case and join it with the rest of sentence, like the following:

desc="please make only the first letter Upper Case, and do not change the rest!"
desc = desc[0].upper()+desc[1:]
print(desc)

The output will be:

Please make only the first letter Upper Case, and do not change the rest!
Memin
  • 3,788
  • 30
  • 31
1

You just have to change one line:

string=input('Enter a sentence/sentences please:')
sentence=string.split('.')
for i in sentence:
    print (i.strip().capitalize()+". ",end='')
austin-schick
  • 1,225
  • 7
  • 11
1

This should work:

import re
text = raw_input("Enter text: ")
rtn = re.split('([.!?] *)', text)
final = ''.join([i.capitalize() for i in rtn])
print final
Stef II
  • 11
  • 1
0

Okay, so my first answer was totally wrong. Here's another answer you can use, and it shows you some of the more powerful features of python, too. Suppose you have your string stored in s, where all your sentences are in a single string delimited by a comma. The following code returns that same exact string, separated by periods, but with the first characters of each sentence capitalized.

'.'.join(map((lambda x: x[0].upper()+x[1:]), s.replace('. ','.').split('.')))

Slick, right?

alvonellos
  • 1,009
  • 1
  • 9
  • 27
0

maybe you can do this:

string=input('Enter a sentence/sentences please:')
sentence='.'.join([i.capitalize() for i in string.split('.')])
print(sentence)
Adam Wen
  • 18
  • 4
0

You can use end='.' in your print function.

print(i.capitalize(),end='.')
Håken Lid
  • 22,318
  • 9
  • 52
  • 67
  • 3
    If your answer is too short to be accepted, it might help to explain the error you were trying to bring up. – artdanil Nov 23 '16 at 05:22
0

It seems that many folks don't bother to check indentation or code by running it first to check for errors. Concerning capitalization of the first word in a sentence that has OTHER WORDS in the sentence that are to REMAIN capitalized, the question must have been lost to others who responded. If you want to accomplish this try the following code which will run on a repeating menu until exit is selected:

# Purpose: Demonstrate string manipulation.
#
# ---------------------------------------------------------------
# Variable          Type        Purpose
# ---------------------------------------------------------------
# strSelection      string      Store value of user selection.
# strName           string      Store value of user input.
# words             string      Accumulator for loop.


def main():
    print()
    print("-----------------------------------------------------")
    print("|             String Manipulation                   |")
    print("-----------------------------------------------------")
    print()
    print("1: String Manipulation")
    print("X: Exit application")
    print()
    strSelection = input("Enter your menu selection: ")
    if strSelection == "1":
        strName = input("Enter sentence(s) of your choosing:  ")
        strSentences = ""
        words = list(strName.split(". ")) # Create list based on each sentence.
        for i  in range(len(words)): # Loop through list which is each sentence.
            words[i] = words[i].strip() # Remove any leading or trailing spaces.
            words[i] = words[i].strip(".") # Remove any periods.

            words[i] = words[i][:1].upper() + words[i][1:] # Concatenate string with first letter upper.
            strSentences += words[i] + ". " # Concatenate a final string with all sentences.

        # Print results.
        print("Sentences with first word capitalized, \
and other caps left intact: ", strSentences) 
        print()
        main() # Redisplay menu.

    # Bid user adieu.
    elif strSelection.upper() == "X":
        print("Goodbye")
    else:
        print ("Invalid selection")
        main() # Redisplay menu.

main()
0

This program uses to capitalize first word of each new sentence.

def sentenceCapitalizer():

    string===input('Enter a sentence/sentences please:')
    sentence=string.split('.')
    for i in sentence:
        print (i.strip().capitalize()+". ",end='')
sentenceCapitalizer()
TheEsnSiavashi
  • 1,245
  • 1
  • 14
  • 29
0

I was having this same issue, after searching and tweaking for hours. I finally find an almost perfect solution, however, it solves the problem in hand.

    original_data = raw_input("Enter text: ")
    list = original_data.split(".")
    if original_data.endswith('.'):
        list.remove('')

    for w in list:
        stripper= w.strip().capitalize() +"."
        print stripper,

What this code does is that it take an input as a string and convert it to string array using the split() function. And then iterate through that array to extract every strings and capitalize the first character after a full stop.

Lets say you input something, like:

hello stackoverflow. hi robot. we're here, devmike.

It would output:

Hello stackoverflow. Hi robot. We're here, devmike.

Note: I only tested this with python2.7+, but you could modify it to work for 3+.

devmike01
  • 1,971
  • 1
  • 20
  • 30
-1

Try this:

x = 'hello. how are you doing. nice to see. you'
print '.'.join(map(lambda x: x.title(), x.split('.')))
Saksham Varma
  • 2,122
  • 13
  • 15
  • This code snippet capitalizes EVERY first letter of a word. Example: Hello. How Are You Doing. Nice To See You. – Nightforce2 Oct 18 '20 at 18:25