Skip to content

Instantly share code, notes, and snippets.

@dcdeve
Forked from ebuckley/gist:1842461
Last active March 13, 2018 18:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcdeve/3dfba6566029f87b01aa3e38d6e1e26b to your computer and use it in GitHub Desktop.
Save dcdeve/3dfba6566029f87b01aa3e38d6e1e26b to your computer and use it in GitHub Desktop.
python code to encode/decode morse code
import sys
import string
morseAlphabet = {
"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" : "-----",
".": ".-.-.-",
",": "--..--",
":": "---...",
"?": "..--..",
"'": ".----.",
"-": "-....-",
"/": "-..-.",
"@": ".--.-.",
"=": "-...-"
}
inverseMorseAlphabet = dict((v, k) for (k, v) in morseAlphabet.items())
testCode = ".... . .-.. .-.. --- / -.. .- .. .-.. -.-- / .--. .-. --- --. .-. .- -- -- . .-. / --. --- --- -.. / .-.. ..- -.-. -.- / --- -. / - .... . / -.-. .... .- .-.. .-.. . -. --. . ... / - --- -.. .- -.--"
# parse a morse code string positionInString is the starting point for decoding
def decodeMorse(message):
messageSeparated = message.split(' ')
decodeMessage = ''
for char in messageSeparated:
if char in inverseMorseAlphabet:
decodeMessage += inverseMorseAlphabet[char]
else:
# CNF = Character not found
decodeMessage += '<CNF>'
return decodeMessage
# encode a message in morse code, spaces between words are represented by '/'
def encodeToMorse(message):
encodedMessage = ""
for char in message[:]:
if char.upper() in morseAlphabet:
encodedMessage += morseAlphabet[char.upper()] + " "
else:
encodedMessage += '<CNF>'
return encodedMessage
@NateAllCodey
Copy link

So to put in a morse code I would just have to put an userinput code or would I have to add more things to be able to use it like that.

@dcdeve
Copy link
Author

dcdeve commented Mar 13, 2018

@NateAllCodey
depends on how you want to use it, if it is by terminal you could add a parameter and transform that.
If you want to use it through the web, you can place it in the package and import it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment