Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two lines if they are not empty

I want to combine 2 lines of text into one, but only when they are both not empty lines. For example:

1:1 Bob drives his car.
1:2 Bob and his wife are going on a trip. 
They will have an awesome time on the beach.

I want to put them into a dictionary like this:

dict[1:1] gives me "Bob drives his car."
and dict[1:2] must give me "Bob and his wife are going on a trip.They will have an awesome time on the beach."

I know how to fix the fist one (dict[1:1]), but I have no idea how I can take the two sentences together.

Or is there an option that if a sentence is followed by another one you can put them on one line? This is just an example in reality , the file contains 100000 lines.

like image 577
Aleandro Avatar asked Jan 19 '26 07:01

Aleandro


1 Answers

You can do it like this - read one line at a time from the file, and where there is a blank line trigger the start of a new section.

start_new_section = True
key = None
output = {}
with open('file.txt', 'r') as f:
    for line in f:
        if line == '':
            start_new_section = True
        elif start_new_section:
            words = line.split(' ')
            key = words[0]
            output[key] = ' '.join(words[1:])
            start_new_section = False
        else:
            output[key] += line

print(output)

Or a tidier version of the same idea:

key = None
output = {}
with open('file.txt', 'r') as f:
    for line in f:
        if not line:
            key = None
        elif key:
            output[key] += line
        else:
            key, _, output[key] = line.partition(' ')
like image 79
Stuart Avatar answered Jan 20 '26 21:01

Stuart