Updated for challenge 9
[cipher-tools.git] / support / text_prettify.py
1 import string
2 from support.segment import segment
3 from support.utilities import cat, lcat, sanitise
4
5
6 def prettify(text, width=100):
7 """Segment a text into words, then pack into lines, and combine the lines
8 into a single string for printing."""
9 return lcat(tpack(segment(text), width=width))
10
11
12 def tpack(text, width=100):
13 """Pack a list of words into lines, so long as each line (including
14 intervening spaces) is no longer than _width_"""
15 lines = [text[0]]
16 for word in text[1:]:
17 if len(lines[-1]) + 1 + len(word) <= width:
18 lines[-1] += (' ' + word)
19 else:
20 lines += [word]
21 return lines
22
23
24 def depunctuate_character(c):
25 """Record the punctuation of a character"""
26 if c in string.ascii_uppercase:
27 return 'UPPER'
28 elif c in string.ascii_lowercase:
29 return 'LOWER'
30 else:
31 return c
32
33
34 def depunctuate(text):
35 """Record the punctuation of a string, so it can be applied to a converted
36 version of the string.
37
38 For example,
39 punct = depunctuate(ciphertext)
40 plaintext = decipher(sanitise(ciphertext))
41 readable_plaintext = repunctuate(plaintext, punct)
42 """
43 return [depunctuate_character(c) for c in text]
44
45
46 def repunctuate_character(letters, punctuation):
47 """Apply the recorded punctuation to a character. The letters must be
48 an iterator of base characters."""
49 if punctuation == 'UPPER':
50 return next(letters).upper()
51 elif punctuation == 'LOWER':
52 return next(letters).lower()
53 else:
54 return punctuation
55
56
57 def repunctuate(text, punctuation):
58 """Apply the recored punctuation to a sanitised string.
59
60 For example,
61 punct = depunctuate(ciphertext)
62 plaintext = decipher(sanitise(ciphertext))
63 readable_plaintext = repunctuate(plaintext, punct)
64 """
65 letters = iter(sanitise(text))
66 return cat(repunctuate_character(letters, p) for p in punctuation)