|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Write a program that will correct an input string to use proper capitalization and spacing. |
| 4 | +# Allowed punctuation are the period ( . ), question mark ( ? ), and exclamation ( ! ). |
| 5 | +# Make sure that single space always follows commas ( , ), colons ( : ), semicolons ( ; ) |
| 6 | +# and all other punctuation. |
| 7 | +# The input string will be a valid English |
| 8 | +# sentence.capitalizeString("first, solve the problem.then, write the code.") |
| 9 | +# // "First, solve the problem. Then, write the code." |
| 10 | +# capitalizeString("this is a test... and another test.") |
| 11 | +# // "This is a test... And another test." |
| 12 | +import re |
| 13 | + |
| 14 | + |
| 15 | +def capitalizeString(S): |
| 16 | + |
| 17 | + def upper_after_dot(m): |
| 18 | + return m[1] + " " + m[2].strip().capitalize() |
| 19 | + |
| 20 | + if S is not None: |
| 21 | + ss = S.strip() |
| 22 | + # first letter |
| 23 | + ss = ss.capitalize() |
| 24 | + # replace more than one space by one space |
| 25 | + ss = re.sub("\s+", " ", ss) |
| 26 | + # fix . spacing |
| 27 | + ss = re.sub(r"([.])(\s{2,*})", r". \2", ss) |
| 28 | + ss = re.sub(r"([.])(\w+)", r". \2", ss) |
| 29 | + # fix , spacing |
| 30 | + ss = re.sub(r"(\,)(\s{2,*})", r", \2", ss) |
| 31 | + ss = re.sub(r"(\,)(\w+)", r", \2", ss) |
| 32 | + # fix ; spacing |
| 33 | + ss = re.sub(r"(\;)(\s{2,*})", r"; \2", ss) |
| 34 | + ss = re.sub(r"(\;)(\w+)", r"; \2", ss) |
| 35 | + # fix : spacing |
| 36 | + ss = re.sub(r"(\:)(\s{2,*})", r": \2", ss) |
| 37 | + ss = re.sub(r"(\:)(\w+)", r": \2", ss) |
| 38 | + # fix ? spacing |
| 39 | + ss = re.sub(r"(\?)(\s{2,*})", r"? \2", ss) |
| 40 | + ss = re.sub(r"(\?)(\w+)", r"? \2", ss) |
| 41 | + # fix ! spacing |
| 42 | + ss = re.sub(r"(\!)(\s{2,*})", r"! \2", ss) |
| 43 | + ss = re.sub(r"(\!)(\w+)", r"! \2", ss) |
| 44 | + # upper case after . |
| 45 | + ss = re.sub(r"([.])(\s[a-z]*)", upper_after_dot, ss) |
| 46 | + |
| 47 | + return ss |
| 48 | + return None |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == '__main__': |
| 52 | + |
| 53 | + print(capitalizeString("first, solve the problem.then, write the code.")) |
| 54 | + assert capitalizeString("first, solve the problem.then, write the code.") \ |
| 55 | + == "First, solve the problem. Then, write the code." |
| 56 | + |
| 57 | + print(capitalizeString("this is a test... and another test.")) |
| 58 | + assert capitalizeString("this is a test... and another test.") \ |
| 59 | + == "This is a test... And another test." |
| 60 | + |
| 61 | + print(capitalizeString("aaaaa bbbbb,ccccc; ddddd.eeeee")) |
| 62 | + assert capitalizeString("aaaaa bbbbb,ccccc; ddddd.eeeee") \ |
| 63 | + == "Aaaaa bbbbb, ccccc; ddddd. Eeeee" |
0 commit comments