Meghdeep Ray Meghdeep Ray - 3 months ago 14
Python Question

Regex - Splitting Strings at full-stops unless it's part of an honorific

I have a list containing all possible titles:

['Mr.', 'Mrs.', 'Ms.', 'Dr.', 'Prof.', 'Rev.', 'Capt.', 'Lt.-Col.', 'Col.', 'Lt.-Cmdr.', 'The Hon.', 'Cmdr.', 'Flt. Lt.', 'Brgdr.', 'Wng. Cmdr.', 'Group Capt.' ,'Rt.', 'Maj.-Gen.', 'Rear Admrl.', 'Esq.', 'Mx', 'Adv', 'Jr.']


I need a Python 2.7 code that can replace all full-stops
\.
with newline
\n
unless it's one of the above titles.

Splitting it into a list of strings would be fine as well.

Sample Input:



Modi is waiting in line to Thank Dr. Manmohan Singh for preparing a road map for introduction of GST in India. The bill is set to pass.


Sample Output:



Modi is waiting in line to Thank Dr. Manmohan Singh for preparing a road map for introduction of GST in India.
The bill is set to pass.

Answer

This should do the trick, here we use a list comprehension with a conditional statement to concatenate the words with a \n if they contain a full-stop, and are not in the list of key words. Otherwise just concatenate a space.

Finally the words in the sentence are joined using join(), and we use rstrip() to eliminate any newline remaining at the end of the string.

l = set(['Mr.', 'Mrs.', 'Ms.', 'Dr.', 'Prof.', 'Rev.', 'Capt.', 'Lt.-Col.', 
'Col.', 'Lt.-Cmdr.', 'The Hon.', 'Cmdr.', 'Flt. Lt.', 'Brgdr.', 'Wng. Cmdr.', 
'Group Capt.' ,'Rt.', 'Maj.-Gen.', 'Rear Admrl.', 'Esq.', 'Mx', 'Adv', 'Jr.'] )
s = 'Modi is waiting in line to Thank Dr. Manmohan Singh for preparing a road 
map for introduction of GST in India. The bill is set to pass.'

def split_at_period(s):
    final = []
    split_l = s.split(' ')

    for w in split_l:
        if '.' in w and w not in l:
            final.append(w + '\n')
            continue
        final.append(w + ' ')

    return ''.join(final).rstrip()

print split_at_period(s)

or a one liner :D

print ''.join([w + '\n' if '.' in w and w not in l else w + ' ' for w in s.split(' ')]).rstrip()

Sample output:

Modi is waiting in line to Thank Dr. Manmohan Singh for preparing a road map for introduction of GST in India.
The bill is set to pass.
Comments