Started on documentation
[szyfrow.git] / szyfrow / support / text_prettify.py
1 """Various functions for prettifying text, useful when cipher routines generate
2 strings of letters without spaces.
3 """
4
5 import string
6 from szyfrow.support.segment import segment
7 from szyfrow.support.utilities import cat, lcat, sanitise
8
9
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))
14
15
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_"""
19 lines = [text[0]]
20 for word in text[1:]:
21 if len(lines[-1]) + 1 + len(word) <= width:
22 lines[-1] += (' ' + word)
23 else:
24 lines += [word]
25 return lines
26
27
28 def depunctuate_character(c):
29 """Record the punctuation of a character"""
30 if c in string.ascii_uppercase:
31 return 'UPPER'
32 elif c in string.ascii_lowercase:
33 return 'LOWER'
34 else:
35 return c
36
37
38 def depunctuate(text):
39 """Record the punctuation of a string, so it can be applied to a converted
40 version of the string.
41
42 For example,
43 punct = depunctuate(ciphertext)
44 plaintext = decipher(sanitise(ciphertext))
45 readable_plaintext = repunctuate(plaintext, punct)
46 """
47 return [depunctuate_character(c) for c in text]
48
49
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()
57 else:
58 return punctuation
59
60
61 def repunctuate(text, punctuation):
62 """Apply the recored punctuation to a sanitised string.
63
64 For example,
65 punct = depunctuate(ciphertext)
66 plaintext = decipher(sanitise(ciphertext))
67 readable_plaintext = repunctuate(plaintext, punct)
68 """
69 letters = iter(sanitise(text))
70 return cat(repunctuate_character(letters, p) for p in punctuation)