Skip to content

Instantly share code, notes, and snippets.

@tryone144
Created January 29, 2018 20:38
Show Gist options
  • Save tryone144/60f46d0c299229a4d9f243ada34e7e4e to your computer and use it in GitHub Desktop.
Save tryone144/60f46d0c299229a4d9f243ada34e7e4e to your computer and use it in GitHub Desktop.
Simple morse-code implementation for strings usings '.' and '-' symbols
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# simple morse-code implementation for strings usings '.' and '-' symbols
#
# (c) 2018 Bernd Busse
import sys
ALPHABET = {
'A': '.-',
'B': '-...',
'C': '-.-.',
'D': '-..',
'E': '.',
'F': '..-.',
'G': '--.',
'H': '....',
'I': '..',
'J': '.---',
'K': '-.-',
'L': '.-..',
'M': '--',
'N': '-.',
'O': '---',
'P': '.--.',
'Q': '--.-',
'R': '.-.',
'S': '...',
'T': '-',
'U': '..-',
'V': '...-',
'W': '.--',
'X': '-..-',
'Y': '-.--',
'Z': '--..',
'1': '.----',
'2': '..---',
'3': '...--',
'4': '....-',
'5': '.....',
'6': '-....',
'7': '--...',
'8': '---..',
'9': '----.',
'0': '-----',
}
INVERSE = {v: k for k, v in ALPHABET.items()}
class EncodingError(RuntimeError):
pass
class DecodingError(RuntimeError):
pass
def usage(executable):
sys.stderr.write("usage: {} -e TEXT\n".format(executable))
sys.stderr.write(" {} -d CODE\n".format(executable))
sys.stderr.flush()
def encode(message):
code = []
for char in message:
if char == ' ':
code.append(" ")
else:
try:
code.append(ALPHABET[char.upper()])
except KeyError as e:
raise EncodingError("Invalid character: '{}'".format(char))
return ' '.join(code)
def decode(code):
message = []
space = False
for char in code.split(' '):
if char == '' and not space:
message.append(' ')
space = True
elif char == '': pass
elif char == '--··--':
message.append("[SP]")
elif char == '·-·-·-':
message.append("[EOM]")
else:
try:
message.append(INVERSE[char])
space = False
except KeyError as e:
raise DecodingError("Invalid character: '{}'".format(char))
return ''.join(message)
if __name__ == '__main__':
if len(sys.argv) != 3:
usage(sys.argv[0])
exit(1)
if sys.argv[1] == "-e":
# Run encoding
code = encode(sys.argv[2])
print("Morsecode: {:s}".format(code))
elif sys.argv[1] == "-d":
# Run decoding
message = decode(sys.argv[2])
print("Message: {:s}".format(message))
else:
usage(sys.argv[0])
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment