-
-
Save dcdeve/3dfba6566029f87b01aa3e38d6e1e26b to your computer and use it in GitHub Desktop.
python code to encode/decode morse code
This file contains 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
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
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
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.