Requirements:
Given a long section of text, where the only indication that a paragraph has ended is a shorter line, make a guess about the first paragraph. The lines are hardwrapped, and the wrapping is consistent for the entire text.
The code below assumes that a paragraph ends with a line that is shorter than the average of all of the other lines. It also checks to see whether the line is shorter merely because of word wrapping by looking at the word in the next line and seeing whether that would have made the line extend beyond the "maximum" width for the paragraph.
def get_first_paragraph(source_text):
lines = source_text.splitlines()
lens = [len(line) for line in lines]
avglen = sum(lens)/len(lens)
maxlen = max(lens)
newlines = []
for line_idx, line in enumerate(lines):
newlines.append(line)
try:
word_in_next_line = lines[line_idx+1].split()[0]
except IndexError:
break # we've reached the last line
if len(line) < avglen and len(line) + 1 + len(word_in_next_line) < maxlen: # 1 is for space between words
break
return '\n'.join(newlines)
Sample #1
Input:
This is a sample paragaraph. It goes on and on for several sentences. Many OF These Remarkable Sentences are Considerable in Length. It has a variety of words with different lengths, and there is not a consistent line length, although it appears to hover supercalifragilisticexpialidociously around the 70 character mark. Ideally the code should recognize that one line is much shorter than the rest, and is shorter not because of a much longer word following it which has wrapped the line, but because we have reached the end of a paragraph. This is the next paragraph, and continues onwards for more and more sentences.
Output:
This is a sample paragaraph. It goes on and on for several sentences. Many OF These Remarkable Sentences are Considerable in Length. It has a variety of words with different lengths, and there is not a consistent line length, although it appears to hover supercalifragilisticexpialidociously around the 70 character mark. Ideally the code should recognize that one line is much shorter than the rest, and is shorter not because of a much longer word following it which has wrapped the line, but because we have reached the end of a paragraph.
Using other sample inputs I see there are a few issues, particularly if the text features a short paragraph or if there is more than one paragraph in the source text (leading to the trailing shorter lines reducing the overall average).
if len(line) + len(word_in_next_line) < maxlen:
would seem better to me. \$\endgroup\$Many OF These Remarkable Sentences are Considerable in Length.
is just 63 characters even though it takes up the whole width. Without the check for average length, it would be falsely identified as a new paragraph. \$\endgroup\$