|
| 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 | + 'dec(tap)': {'.... .... .. ... .. .... .... ... .. .... .... ... . . .... .... . ..... .... ... .... ....' : 'thisisatest'} |
| 16 | +} |
| 17 | + |
| 18 | + |
| 19 | +def build_encmap(map) : |
| 20 | + dict = {} |
| 21 | + i = 0 |
| 22 | + for col in range(1,6) : |
| 23 | + for row in range(1,6) : |
| 24 | + dict[map[i]] = "" + col * "." + " " + row * "." |
| 25 | + i += 1 |
| 26 | + dict['k'] = dict['c'] |
| 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 | + try : |
| 35 | + encoded += ENCMAP[letter.lower()] |
| 36 | + except KeyError : |
| 37 | + pass |
| 38 | + if i != len(text) - 1 and letter != ' ': |
| 39 | + encoded += ' ' |
| 40 | + return encoded, len(text) |
| 41 | + |
| 42 | + |
| 43 | +def decode_tap(text, errors = 'ignore') : |
| 44 | + map = 'abcdefghijlmnopqrstuvwxyz' |
| 45 | + ENCMAP = build_encmap(map) |
| 46 | + decoded = "" |
| 47 | + for elem in text.split(" ") : |
| 48 | + try : |
| 49 | + decoded += next(key for key, value in ENCMAP.items() if value == elem) |
| 50 | + except StopIteration : |
| 51 | + print("Invalid character(s) in the input. This is what could be decoded :") |
| 52 | + return decoded, len(text) |
| 53 | + |
| 54 | + |
| 55 | +add("tap", encode_tap, decode_tap, ignore_case="both") |
| 56 | + |
0 commit comments