I'm trying to figure out how to have a text file with a word in morse code in it and have my program decode it and print it out. I've managed to do the opposite where a word is in the text file and it's morse equivalent is printed out. I'm using a dictionary for the key:value of the morse, then I'm reversing the order and have a 'for' loop to run through the dict, and an 'if' statement to check the text file, then compare them.
If I enter this in the text file: -... .- --.
I'd like the program to print out:
b a d
The loop is reading each dot and dash in data.txt as seperate items so
if it it contains '.-' which is the letter 'a', instead it looks through
the dictionary for anything containing '.' and/or '-' so it would actually print each letter in morsedict twice, except for 'e', just once since it doesn't contain a dash but does a dot.
If I enter this in the text file: -... .- --.
I'd like the program to print out:
b a d
Code:
# I've shortened the dict{} for this example # data.txt will contain morse code such as .- which is just the letter 'a' f = open("data.txt","r") text = f.read() morsedict = {'a': '.-', 'b':'-...', 'c':'-.-.', 'd':'--.', 'e':'.'} # reversing the order of the keys and values reverse_morse = dict((code, letter) for (letter, code) in morsedict.items()) #check key and value, then comparing to data. If found, just print the value for k, v in reverse_morse.iteritems(): for item in text: if item in k: print v
if it it contains '.-' which is the letter 'a', instead it looks through
the dictionary for anything containing '.' and/or '-' so it would actually print each letter in morsedict twice, except for 'e', just once since it doesn't contain a dash but does a dot.
Comment