/
boxea.py
executable file
·90 lines (71 loc) · 2.79 KB
/
boxea.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
#!/usr/bin/env python3
# encoding: utf-8
from __future__ import unicode_literals
import sys
from itertools import chain, islice
from operator import itemgetter
# for Py2 and Py3 compatibility
try:
unicode
except NameError:
def unicode(x, *args, **kwargs):
return str(x)
try:
from itertools import izip_longest as zipl
except ImportError:
from itertools import zip_longest as zipl
symbols = dict(
se='┌', swe='┬', sw='┐', SE='╔', SWE='╦', SW='╗',
nse='├', nswe='┼', nsw='┤', NSE='╠', NSWE='╬', NSW='╣',
ne='└', nwe='┴', nw='┘', NE='╚', NWE='╩', NW='╝',
sE='╒', sWE='╤', sW='╕', Se='╓', Swe='╥', Sw='╖',
nsE='╞', nsWE='╪', nsW='╡', NSe='╟', NSwe='╫', NSw='╢',
nE='╘', nWE='╧', nW='╛', Ne='╙', Nwe='╨', Nw='╜',
ns='│', we='─', NS='║', WE='═',
n='╵', s='╷',
w='╴', e='╶',
)
def flatten(lists):
return list(chain(*lists))
def neighbors(text):
'''Return iterables n, s, w and e of neighbors of text.
For a given text, return four character-yielding iterables that are
respectively the neighbors above, below, to the left and to the right of
the corresponding character in the text. Inexistant neighbors are
represented by None.
'''
lines = text.splitlines(True)
n = [None for _ in lines[0]] + flatten([
map(itemgetter(0), islice(zipl(prev_line, line), len(line)))
for prev_line, line in zip(lines, lines[1:])
])
s = flatten([
map(itemgetter(1), islice(zipl(line, next_line), len(line)))
for line, next_line in zip(lines, lines[1:])
]) + [None for _ in lines[-1]]
w = flatten([[None] + list(line[:-1]) for line in lines])
e = flatten([list(line[1:]) + [None] for line in lines])
return n, s, w, e
def ascii_to_box(text, vertical='|', horizontal='-', intersection='+'):
new_text_characters = []
for char, cn, cs, cw, ce in zip(text, *neighbors(text)):
new_char = ''
if char == vertical:
new_char = symbols['ns']
elif char == horizontal:
new_char = symbols['we']
elif char == intersection:
key = (('n' if cn in [intersection, vertical] else '') +
('s' if cs in [intersection, vertical] else '') +
('w' if cw in [intersection, horizontal] else '') +
('e' if ce in [intersection, horizontal] else ''))
new_char = symbols[key] if key else char
else:
new_char = char
assert len(new_char) == 1
new_text_characters.append(new_char)
return ''.join(new_text_characters)
def main():
print(ascii_to_box(unicode(sys.stdin.read(), encoding='utf-8')))
if __name__ == '__main__':
main()