Home > Software design >  How can I identify sentences that have a space before a dot '.' and remove this space
How can I identify sentences that have a space before a dot '.' and remove this space

Time:05-20

Given a random text, how can I identify sentences that have a space before a dot '.', and remove this space?

my_text = 'The pressure is already being monitored. We will report the results soon . kind regards.'

Expected result (We will report the results soon . => We will report the results soon.):

my_text = 'The pressure is already being monitored. We will report the results soon. kind regards.'

CodePudding user response:

import re

my_text = 'The pressure is already being monitored. We will report the results soon . kind regards.'

res = re.sub(r'\s \.', r'.', my_text)
print(res)

CodePudding user response:

k=[]                          # Take an empty list
for x in my_text.split('.'):  # Split with all the '.'
  if x==0:                    # For the First iteration do not add '.'
    k.append(x.rstrip())      # rstrip() will remove any number of extra spaces
  else:
    k.append(x.rstrip() '.')  # Add '.' after each sentence.
''.join(k[:-1])               # Removing the last '.' since it will be inserted twice
  • Related