Advertisement
acclivity

pyCorrectSentences

Jun 15th, 2022
875
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. intext = "mary ,  had a little   lamb!!isn't it cute ??!!   it followed  her to school;; ate all her sandwiches. oh dear"
  2.  
  3. newtext = ""
  4.  
  5. start_sentence = True
  6. spctr = 1
  7. lastch = " "
  8. lastnonsp = ""
  9.  
  10. for ch in intext:
  11.     if start_sentence:
  12.         if ch in [".", "!", "?"]:
  13.             if ch == lastch:
  14.                 continue
  15.             if lastch == " ":
  16.                 newtext = newtext.rstrip(' ')
  17.             lastch = ch
  18.             newtext += ch
  19.             newtext += " "
  20.             spctr = 1
  21.             continue
  22.         if ch == ' ':
  23.             spctr += 1
  24.             if spctr == 1:
  25.                 newtext += ch
  26.             lastch = ch
  27.             continue
  28.         if not spctr:
  29.             newtext += " "
  30.         ch = ch.upper()
  31.         newtext += ch
  32.         start_sentence = False
  33.         lastch = ch
  34.         continue
  35.  
  36.     if ch in [".", "!", "?"]:
  37.         if lastch == " ":
  38.             newtext = newtext.rstrip()
  39.         start_sentence = True
  40.     if ch in [',', ':', ';']:
  41.         if lastnonsp == ch:
  42.             continue
  43.         newtext = newtext.rstrip()
  44.         newtext += ch
  45.         newtext += " "
  46.         lastnonsp = ch
  47.         lastch = " "
  48.         continue
  49.     if ch == " " and lastch == " ":
  50.         continue
  51.  
  52.     if ch != " ":
  53.         spctr = 0
  54.  
  55.     lastch = ch
  56.     newtext += ch
  57.  
  58. # ensure sentence ends with a sentence terminator
  59. newtext = newtext.rstrip()
  60. if newtext[-1] not in [".", "!", "?"]:
  61.     newtext += "."
  62. print(newtext)
  63.  
  64. # in = "mary ,  had a little   lamb!!isn't it cute ??!!   it followed  her to school;; ate all her sandwiches. oh dear"
  65. # Out: "Mary, had a little lamb! Isn't it cute?! It followed her to school; ate all her sandwiches. Oh dear."
  66.  
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement