forked from dhondta/python-codext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtap.py
56 lines (45 loc) · 1.63 KB
/
tap.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
# -*- coding: UTF-8 -*-
"""Tap code - Tap/knock code encoding.
This codec:
- en/decodes strings from str to str
- en/decodes strings from bytes to bytes
- decodes file content to str (read)
- encodes file content from str to bytes (write)
"""
from ..__common__ import *
__examples__ = {
'enc(tap)': {'this is a test' : '.... .... .. ... .. .... .... ... .. .... .... ... . . .... .... . ..... .... ... .... ....'},
'dec(tap)': {'.... .... .. ... .. .... .... ... .. .... .... ... . . .... .... . ..... .... ... .... ....' : 'thisisatest'}
}
def build_encmap(map) :
dict = {}
i = 0
for col in range(1,6) :
for row in range(1,6) :
dict[map[i]] = "" + col * "." + " " + row * "."
i += 1
dict['k'] = dict['c']
return dict
def encode_tap(text, errors = 'strict') :
map = 'abcdefghijlmnopqrstuvwxyz'
ENCMAP = build_encmap(map)
encoded = ""
for i, letter in enumerate(text) :
try :
encoded += ENCMAP[letter.lower()]
except KeyError :
pass
if i != len(text) - 1 and letter != ' ':
encoded += ' '
return encoded, len(text)
def decode_tap(text, errors = 'ignore') :
map = 'abcdefghijlmnopqrstuvwxyz'
ENCMAP = build_encmap(map)
decoded = ""
for elem in text.split(" ") :
try :
decoded += next(key for key, value in ENCMAP.items() if value == elem)
except StopIteration :
print("Invalid character(s) in the input. This is what could be decoded :")
return decoded, len(text)
add("tap", encode_tap, decode_tap, ignore_case="both")