Split a text into paragraphs and wrap them to width linelength. Optionally justify the paragraphs (i.e. stretch lines to fill width). Inter-word space is reduced to one space character and paragraphs are always separated by two newlines. Indention is currently also lost.
(text, width=80, justify=0)
| 31 | |
| 32 | |
| 33 | def fill_paragraphs(text, width=80, justify=0): |
| 34 | """Split a text into paragraphs and wrap them to width linelength. |
| 35 | |
| 36 | Optionally justify the paragraphs (i.e. stretch lines to fill width). |
| 37 | |
| 38 | Inter-word space is reduced to one space character and paragraphs are |
| 39 | always separated by two newlines. Indention is currently also lost. |
| 40 | |
| 41 | """ |
| 42 | # split taxt into paragraphs at occurences of two or more newlines |
| 43 | paragraphs = re.split(r'\n\n+', text) |
| 44 | for i in range(len(paragraphs)): |
| 45 | # split paragraphs into a list of words |
| 46 | words = paragraphs[i].strip().split() |
| 47 | line = []; new_par = [] |
| 48 | while 1: |
| 49 | if words: |
| 50 | if len(' '.join(line + [words[0]])) > width and line: |
| 51 | # the line is already long enough -> add it to paragraph |
| 52 | if justify: |
| 53 | # stretch line to fill width |
| 54 | new_par.append(justify_line(line, width)) |
| 55 | else: |
| 56 | new_par.append(' '.join(line)) |
| 57 | line = [] |
| 58 | else: |
| 59 | # append next word |
| 60 | line.append(words.pop(0)) |
| 61 | else: |
| 62 | # last line in paragraph |
| 63 | new_par.append(' '.join(line)) |
| 64 | line = [] |
| 65 | break |
| 66 | # replace paragraph with formatted version |
| 67 | paragraphs[i] = '\n'.join(new_par) |
| 68 | # return paragraphs separated by two newlines |
| 69 | return '\n\n'.join(paragraphs) |
| 70 | |
| 71 | |
| 72 | def _test(width=78, justify=1): |