-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
icebox.py
executable file
·110 lines (90 loc) · 2.59 KB
/
icebox.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python
"""
Replace all words with plums, preserving punctuation.
For NaNoGenMo ~2014~ 2017.
~https://github.com/dariusk/NaNoGenMo-2014/~
https://github.com/NaNoGenMo/2017
"""
import argparse
import random
import re
import sys
def is_word(thing):
found = re.match(r"\w+", thing, re.UNICODE)
return found
def plum_plum(line, converter_fun):
"""Plumify a line"""
plummed = []
# Break line into words and non-words (e.g. punctuation and space)
things = re.findall(r"\w+|[^\w]", line, re.UNICODE)
for thing in things:
if is_word(thing):
plummed.append(converter_fun(thing))
else:
plummed.append(thing)
return "".join(plummed)
def plum(word):
"""Plumify a word"""
plummed = ""
length = len(word)
if length == 1:
return capify("p", word)
elif length == 2:
return capify("pl", word)
elif length == 3:
return capify("plm", word)
elif length == 4:
return capify("plum", word)
# Words longer than four will have:
# * first letter P
# * last letter M
# * middle with a random number of Ls, then some Us
# Number of LUs:
elyous = length - len("p") - len("m")
# Number of Ls:
els = random.randrange(1, elyous)
# Number of Os:
yous = elyous - els
plummed = "p" + ("l" * els) + ("u" * yous) + "m"
return capify(plummed, word)
def capify(word, reference):
"""Make sure word has the same capitalisation as reference"""
new_word = ""
# First check whole word before char-by-char
if reference.islower():
return word.lower()
elif reference.isupper():
return word.upper()
# Char-by-char checks
for i, c in enumerate(reference):
if c.isupper():
new_word += word[i].upper()
else:
new_word += word[i]
return new_word
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Replace all words with plums, preserving punctuation."
)
parser.add_argument(
"infile",
nargs="?",
type=argparse.FileType("r"),
default=sys.stdin,
help="Input text",
)
parser.add_argument(
"-t",
"--translation",
action="store_true",
help="Output a line-by-line translation",
)
args = parser.parse_args()
# for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")):
for line in args.infile:
line = line.rstrip() # No BOM
if args.translation:
print()
print(line)
print(plum_plum(line, plum))
# End of file