Uppercasing Letters After '.', '!' And '?' Signs In Python
I have been searching Stack Overflow but cannot find the proper code for correcting e.g. 'hello! are you tired? no, not at all!' Into: 'Hello! Are you tired? No, not at all!'
Solution 1:
You can try this regex approach:
import re
re.sub("(^|[.?!])\s*([a-zA-Z])", lambda p: p.group(0).upper(), s)
# 'Hello! Are you tired? No, not at all!'
(^|[.?!])
matches the start of the string^
or.?!
followed by optional spaces;[a-zA-Z]
matches letter directly after the first pattern;- use lambda function to convert the captured group to upper case;
Solution 2:
- Use regular expressions to split at punctuation characters
- Join everything back with capitalized letters at the start of the sentences.
For example like this:
importretext='hello! are you tired? no, not at all!'
punc_filter = re.compile('([.!?]\s*)')
split_with_punctuation = punc_filter.split(text)
final = ''.join([i.capitalize() for i in split_with_punctuation])
print(final)
Output:
>>>Hello! Are you tired? No, not at all!
Solution 3:
capitalize() method makes all letters small except the first one.
More general variant is:
def capitalize(text):
punc_filter = re.compile('([.!?;]\s*)')
split_with_punctuation = punc_filter.split(text)
for i,j in enumerate(split_with_punctuation):
if len(j) > 1:
split_with_punctuation[i] = j[0].upper() + j[1:]
text = ''.join(split_with_punctuation)
return text
text = "hello Bob! are you tired? no, not at all!"capitalize(text)
Output:
'Hello Bob! Are you tired? No, not at all!'
Solution 4:
You could do something like
x = "hello! are you tired? no, not at all!"
y = x.split("? ")
z=""
for line in y:
z = "{} {}".format(z,line.capitalize())
print(z)
And adjust it to your needs.
Post a Comment for "Uppercasing Letters After '.', '!' And '?' Signs In Python"