Combine multiple lines when one doesn't end with a dot

Viewed 115

I am cleaning up some subtitles text and I am looking for a way to combine in a single line different lines, when they don't end with a ".". Considering the example

No, he's building one actually. 
Baller. 
Anyway, he's also offering a hundred k to people willing to skip or drop out of college
To pursue their idea.

I would like to convert it into

No, he's building one actually. 
Baller. 
Anyway, he's also offering a hundred k to people willing to skip or drop out of college to pursue their idea.

So that every line ends with a dot. Do you have suggestions on how to implement this?

2 Answers

One option is to use a lookbehind to assert for example a lowercase char a-z, then match the newline and use a capture group for an uppercase char A-Z on the next line.

In the replacement use lower() on the capture group and prepend a space so that the matched newline is not part of the replacement.

import re

s = ("No, he's building one actually. \n"
                "Baller. \n"
                "Anyway, he's also offering a hundred k to people willing to skip or drop out of college\n"
                "To pursue their idea.")

s = re.sub(r"(?<=[a-z])\r?\n([A-Z])", lambda x: " " + x.group(1).lower(), s)
print(s)

Output

No, he's building one actually. 
Baller. 
Anyway, he's also offering a hundred k to people willing to skip or drop out of college to pursue their idea.

Another option could be for example to assert a non whitspace char except a dot [^\s.] to the left to make it a bit broader.

(?<=[^\s.])\r?\n([A-Z])

codes:

file = open("your_file_name.txt","r").readlines()

list_1 = []
list_2 = []

for i in file:
    if i[-1] == "\n":
        list_1.append(i[:-1])
    else:
        list_1.append(i)

count = 0
not_add_count = None
for i in list_1:
    if count != not_add_count:
        if i[-1] == ".":
            list_2.append(i)
        else:
            list_2.append(i+" "+list_1[count+1].lower())
            not_add_count=count+1


    count +=1

for i in list_2:
    print(i)

summary:

we separated the line break headers at first.We put the dot ending in a separate list (unless this sentence comes after a sentence that does not end with a dot, the purpose of not_add_count is to indicate the location of this sentence). then we printed everything that was filtered clean.

NOTE:

The purpose in this answer is just to show another way

Related