Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@NateAllCodey

NateAllCodey Feb 9, 2018

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.

NateAllCodey commented Feb 9, 2018

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

This comment has been minimized.

Show comment
Hide comment
@dcdeve

dcdeve 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.

Owner

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