Not only a Morse Code Generator but we also allow the user to store his morse code into a txt-file – if he asks nicely.
The terminal output looks like this
The saved file looks like this:
This program takes the topic of yesterday „Dictionaries“ to a new level, since the Morse Code is saved in a dictionary.
This is the program. We have two functions: One generates the code and the other handles the writing and saving to a file.
from morse_dictionary import morse # this is where the morse dictionary is stored
# we give the user the chance to save their morse code to a text file
def save_txt(txt_morse):
if (input("Do you want to save your text to a file? (y/n)")=="y"):
filename = input("Give the file a name: ")
if (filename==""): # if user enters no file name we called it "morse.txt" by default
filename = "morse"
file = open(filename+".txt","w") #opens or creates a txt-file
file.write(txt_morse) # write the morse code to the file
file.close() # close the file again
# the function takes in the plain text and converts it to morse code with the morse dictionary
def morse_gen(text):
txt_upper = text.upper() # since our dictionary only undertands capital letters
txt_morse = ""
for x in (txt_upper):
# we get the morse code for every letter and add it to txt_morse
# we also include two spaces after every letter to make the formatting clearer
txt_morse += morse.get(x, x) + " "
print(txt_morse) # print the morse code
save_txt(txt_morse) # call the save to file function
if (input("Do you want to enter another message? (y/n)")=="y"):
morse_gen(input("Enter the sentence you want to translate (A-Z,a-z,0-9): "))
else:
raise SystemExit #proper program exit
print("*****************************************")
print("**** Morse Code Generator 1912 Model ****")
print("*****************************************")
morse_gen(input("Enter the sentence you want to translate (A-Z,a-z,0-9): "))
This is the Morse Dictionary:
morse = {
"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" : "--..",
"0" : "-----",
"1" : ".----",
"2" : "..---",
"3" : "...--",
"4" : "....-",
"5" : ".....",
"6" : "-....",
"7" : "--...",
"8" : "---..",
"9" : "----.",
"." : ".-.-.-",
"," : "--..--"
}