Last active
December 16, 2016 11:25
-
-
Save yue82/6173bdbe26fc17fc7818f12b55092134 to your computer and use it in GitHub Desktop.
OccuRUtic;Nine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| class BaudotCodec(): | |
| encodes = {} | |
| decodes = {} | |
| ltr_trans_rule = {'保留域': 'NA', | |
| 'SPACE': ' ', | |
| 'LINE_FEED': '\n'} | |
| def __init__(self, filename='bc-list.txt'): | |
| with open(filename, 'r') as f: | |
| for line in f: | |
| code, ltr, fig = (line.strip().split(' ')+['dummy'])[:3] | |
| if ltr in self.ltr_trans_rule: | |
| ltr = self.ltr_trans_rule[ltr] | |
| if fig in self.ltr_trans_rule: | |
| fig = self.ltr_trans_rule[fig] | |
| elif fig == 'dummy': | |
| fig = ltr | |
| self.encodes[ltr] = (code, False) | |
| self.encodes[fig] = (code, True) | |
| self.decodes = {v: k for k, v in self.encodes.items()} | |
| def encode(self, plaintext, bits='01'): | |
| wasfig = False | |
| codetext = '' | |
| for p in plaintext: | |
| code, isfig = self.encodes[p.upper()] | |
| if not wasfig and isfig: | |
| codetext += self.encodes['FIGS'][0] | |
| elif wasfig and not isfig: | |
| codetext += self.encodes['LTRS'][0] | |
| wasfig = isfig | |
| codetext += code | |
| if bits != '01': | |
| codetext = codetext.translate(str.maketrans('01', bits)) | |
| return codetext | |
| def decode(self, codetext, bits='01'): | |
| isfig = False | |
| plaintext = '' | |
| if bits != '01': | |
| codetext = codetext.translate(str.maketrans(bits, '01')) | |
| for i in range(0, len(codetext), 5): | |
| code = codetext[i: i+5] | |
| if code == self.encodes['FIGS'][0]: | |
| isfig = True | |
| elif code == self.encodes['LTRS'][0]: | |
| isfig = False | |
| else: | |
| plaintext += self.decodes[(code, isfig)] | |
| return plaintext |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 00000 NULL | |
| 00001 E 3 | |
| 00010 LINE_FEED | |
| 00011 A - | |
| 00100 SPACE | |
| 00101 S ' BELL | |
| 00110 I 8 | |
| 00111 U 7 | |
| 01000 CARRIAGE_RETURN | |
| 01001 D ENQ $ | |
| 01010 R 4 | |
| 01011 J BELL ' | |
| 01100 N , | |
| 01101 F 保留域 ! | |
| 01110 C : | |
| 01111 K ( | |
| 10000 T 5 | |
| 10001 Z + " | |
| 10010 L ) | |
| 10011 W 2 | |
| 10100 H 保留域 STOP | |
| 10101 Y 6 | |
| 10110 P 0 | |
| 10111 Q 1 | |
| 11000 O 9 | |
| 11001 B ? | |
| 11010 G 保留域 & | |
| 11011 FIGS | |
| 11100 M . | |
| 11101 X / | |
| 11110 V ; | |
| 11111 LTRS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment