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)
| 7 | import re, random |
| 8 | |
| 9 | def 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 | |
| 33 | def fill_paragraphs(text, width=80, justify=0): |