|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +"""Tap code - Tap/knock code encoding. |
| 3 | +
|
| 4 | +This codec: |
| 5 | +- en/decodes strings from str to str |
| 6 | +- en/decodes strings from bytes to bytes |
| 7 | +- decodes file content to str (read) |
| 8 | +- encodes file content from str to bytes (write) |
| 9 | +""" |
| 10 | +from ..__common__ import * |
| 11 | + |
| 12 | + |
| 13 | +__examples__ = { |
| 14 | + 'enc(tap)': {'this is a test': ".... .... .. ... .. .... .... ... .. .... .... ... . . .... .... . ..... .... ... .... ...."} |
| 15 | +} |
| 16 | + |
| 17 | + |
| 18 | +def build_encmap(map) : |
| 19 | + dict = {} |
| 20 | + i = 0 |
| 21 | + for col in range(1,6) : |
| 22 | + for row in range(1,6) : |
| 23 | + dict[map[i]] = "" + col * "." + " " + row * "." |
| 24 | + i += 1 |
| 25 | + dict['k'] = dict['c'] |
| 26 | + dict[' '] = '' |
| 27 | + return dict |
| 28 | + |
| 29 | +def encode_tap(text, errors = 'strict') : |
| 30 | + map = 'abcdefghijlmnopqrstuvwxyz' |
| 31 | + ENCMAP = build_encmap(map) |
| 32 | + encoded = "" |
| 33 | + for i, letter in enumerate(text) : |
| 34 | + encoded += ENCMAP[letter.lower()] |
| 35 | + if i != len(text) - 1 and letter != ' ': |
| 36 | + encoded += ' ' |
| 37 | + return encoded, len(text) |
| 38 | + |
| 39 | + |
| 40 | +def decode_tap(text, errors = 'strict') : |
| 41 | + map = 'abcdefghijlmnopqrstuvwxyz' |
| 42 | + ENCMAP = build_encmap(map) |
| 43 | + decoded = "" |
| 44 | + for elem in text.split(" ") : |
| 45 | + decoded += next(key for key, value in ENCMAP.items() if value == elem) |
| 46 | + return decoded, len(text) |
| 47 | + |
| 48 | + |
| 49 | +add("tap", encode_tap, decode_tap, ignore_case="encode") |
| 50 | + |
0 commit comments