Raj Raj - 15 days ago 7
Python Question

How remove line space from file python

I have a file like this.

Girl: I am girl.

Boy:

I am boy


I am using this code to remove line space.

import string
from itertools import ifilter, imap
print '\n'.join(ifilter(None, imap(string.strip, open('doc1.txt'))))


Using this it is giving me this output.

Girl: I am girl.
Boy:
I am boy


It is not removing space between
Boy:
and
I am boy
. How I can remove that line space? I want output in this format.

Girl: I am girl.
Boy: I am boy.

Answer

Regex should get close. Unfortunately, has to read the whole file content to a string.

import re

test_str = '''Girl: I am girl.

Boy:

I am boy

Dog: Bark

Cat: 

Meow'''

regex = r':\s*\n+'
subst = ": "

for line in re.sub(regex, subst, test_str, 0, re.MULTILINE).split('\n'):
    if line != '':
        print (line.strip())

Output

Girl: I am girl.
Boy: I am boy
Dog: Bark
Cat: Meow
Comments