MCPcopy Create free account
hub / github.com/ActiveState/code / fill_paragraphs

Function fill_paragraphs

recipes/Python/134571_Fill_paragraph/recipe-134571.py:33–69  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

31
32
33def 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
72def _test(width=78, justify=1):

Callers 1

_testFunction · 0.85

Calls 7

rangeFunction · 0.85
justify_lineFunction · 0.85
splitMethod · 0.45
stripMethod · 0.45
joinMethod · 0.45
appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected