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

Function justify_line

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

Stretch a line to width by filling in spaces at word gaps. The gaps are picked randomly one-after-another, before it starts over again.

(line, width)

Source from the content-addressed store, hash-verified

7import re, random
8
9def justify_line(line, width):
10 """Stretch a line to width by filling in spaces at word gaps.
11
12 The gaps are picked randomly one-after-another, before it starts
13 over again.
14
15 """
16 i = []
17 while 1:
18 # line not long enough already?
19 if len(' '.join(line)) < width:
20 if not i:
21 # index list is exhausted
22 # get list if indices excluding last word
23 i = range(max(1, len(line)-1))
24 # and shuffle it
25 random.shuffle(i)
26 # append space to a random word and remove its index
27 line[i.pop(0)] += ' '
28 else:
29 # line has reached specified width or wider
30 return ' '.join(line)
31
32
33def fill_paragraphs(text, width=80, justify=0):

Callers 1

fill_paragraphsFunction · 0.85

Calls 5

rangeFunction · 0.85
maxFunction · 0.50
joinMethod · 0.45
shuffleMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected