1 """Various functions for prettifying text, useful when cipher routines generate
2 strings of letters without spaces.
6 from szyfrow
.support
.segment
import segment
7 from szyfrow
.support
.utilities
import cat
, lcat
, sanitise
10 def prettify(text
, width
=100):
11 """Segment a text into words, then pack into lines, and combine the lines
12 into a single string for printing."""
13 return lcat(tpack(segment(text
), width
=width
))
16 def tpack(text
, width
=100):
17 """Pack a list of words into lines, so long as each line (including
18 intervening spaces) is no longer than _width_"""
21 if len(lines
[-1]) + 1 + len(word
) <= width
:
22 lines
[-1] += (' ' + word
)
28 def depunctuate_character(c
):
29 """Record the punctuation of a character"""
30 if c
in string
.ascii_uppercase
:
32 elif c
in string
.ascii_lowercase
:
38 def depunctuate(text
):
39 """Record the punctuation of a string, so it can be applied to a converted
40 version of the string.
43 punct = depunctuate(ciphertext)
44 plaintext = decipher(sanitise(ciphertext))
45 readable_plaintext = repunctuate(plaintext, punct)
47 return [depunctuate_character(c
) for c
in text
]
50 def repunctuate_character(letters
, punctuation
):
51 """Apply the recorded punctuation to a character. The letters must be
52 an iterator of base characters."""
53 if punctuation
== 'UPPER':
54 return next(letters
).upper()
55 elif punctuation
== 'LOWER':
56 return next(letters
).lower()
61 def repunctuate(text
, punctuation
):
62 """Apply the recored punctuation to a sanitised string.
65 punct = depunctuate(ciphertext)
66 plaintext = decipher(sanitise(ciphertext))
67 readable_plaintext = repunctuate(plaintext, punct)
69 letters
= iter(sanitise(text
))
70 return cat(repunctuate_character(letters
, p
) for p
in punctuation
)