Reputation: 420
i want to convert Morse Code to English using Python 3+ I have managed to convert english to morse code using this http://code.activestate.com/recipes/578407-simple-morse-code-translator-in-python/
But i want to convert Morse Code to English
I have attempted to do it one charecter at a time, but the problem is that morse code letters are not 1 charecter long like english letters, so E is "." and S is "...", the problem i have is that the dictionary loop will find the "." and match it to E, so instead of getting S i get "E E E" i tried to fix this by detecting spaces and doing it a word at a time, but instead of looking for the letters in the word it searches the entire word against the dictionary i'm new to Python and dictionaries and i don't know how to differeniate between an E "." and an S "..." when searching my dictionary
Here is my code
# defines the dictionary to convert morse to english
CODE_reversed = {'..-.': 'F', '-..-': 'X',
'.--.': 'P', '-': 'T', '..---': '2',
'....-': '4', '-----': '0', '--...': '7',
'...-': 'V', '-.-.': 'C', '.': 'E', '.---': 'J',
'---': 'O', '-.-': 'K', '----.': '9', '..': 'I',
'.-..': 'L', '.....': '5', '...--': '3', '-.--': 'Y',
'-....': '6', '.--': 'W', '....': 'H', '-.': 'N', '.-.': 'R',
'-...': 'B', '---..': '8', '--..': 'Z', '-..': 'D', '--.-': 'Q',
'--.': 'G', '--': 'M', '..-': 'U', '.-': 'A', '...': 'S', '.----': '1'}
def main():
#takes user message and makes it upper case
msg = input('MESSAGE: ')
msg = msg.upper()
addtolist = "" # creates blank string
message = [] # creates blank list
for i in msg:
addtolist = addtolist + i # adds every letter in MSG into a string until it finds a space
addtolist.upper() # makes every letter uppercase
if i == " ": # if it detects a space
message.extend(addtolist)
# adds the previously created addtolist to a list, this makes one word
addtolist = "" # clears previous variable
for i in message:
# for every word in the list
str(i) # make it into a string
print(CODE_reversed[i()]) # search the dictionary for that word
if __name__ == "__main__":
main()
This code takes a word, and tries to look it up against the dictionary, but it doesn't work i have also tried searching each individual morse code letter against the dictionary but the problem is that you can't tell when a letter starts and ends, so "..." comes out as "EEE" instead of "S" and i don't know how to fix this
i have also tried searching for solutions but have only found them in Java and i do not know Java
Upvotes: 11
Views: 32952
Reputation:
I know this is an old question but in the tradition of open source I wrote code to implement the fact that Morse is a binary tree and this may be faster than using a dictionary:
class node:
def __init__(self, char):
self.dot = None
self.dash = None
self.alpha = char
def __str__(self):
return self.alpha
def nextNode(self, basenode, char):
if char == '.' and basenode.dot is None:
basenode.dot = node('*')
return basenode.dot
elif char == '.':
return basenode.dot
elif char == '-' and basenode.dash is None:
basenode.dash = node('*')
return basenode.dash
elif char == '-':
return basenode.dash
else:
return basenode
def traverse(self, basenode, tone):
current = basenode
for char in tone:
current = self.nextNode(current, char)
return current
def insert(self, basenode, key): # @ val = tuple ('P','.--.')
char = self.traverse(basenode, key[1])
char.alpha = key[0]
def decode(self, basenode, tone): #@ tone is a morse string
return self.traverse(basenode, tone).alpha
class morse:
def __init__(self, char):
self.base = node(char)
self.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': '--..',
'1': '.----', '2': '..---', '3': '...--',
'4': '....-', '5': '.....', '6': '-....',
'7': '--...', '8': '---..', '9': '----.',
'0': '-----', ', ': '--..--', '.': '.-.-.-',
'?': '..--..', '/': '-..-.', '-': '-....-',
'(': '-.--.', ')': '-.--.-', ' ': ' '}
for x in self.MORSE:
self.base.insert(self.base, (x, self.MORSE.get(x)))
def translate(self, tone):
return self.base.decode(self.base, tone)
def __str__(self):
print(self.base)
return
y = morse(' ')
code = ["-.-.", '.-.', '-.--', '.-.-.-', ' ', '--', '.', '.-.-.-', ' ', '.-',
'.-.-.-', ' ', '.-.', '..', '...-', '.', '.-.', '.-.-.-']
line =[]
for char in code:
line.append(y.translate(char))
print(*line)
this could likely be much more efficient if for instance the dictionary was presorted into the correct order starting with 'E' & 'T' then we would not have to build the tree the way I did. and I am very new to python so likely there are other ways to do this, but this works. I plan to add a function that can listen to live code and translate.
Upvotes: 0
Reputation: 37
mor = {'.-': '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'}
print('''Enter your msg in Morse.
Notic that:
1- Use / to separate the letters and space to separate words.
2- Your message must contain only letters and numbers.
3- '?' in output means that your input was unknowed.
>>> ''', end = '')
msg = input(' ')
out = []
letter = []
j = -1
for i in msg.split(' '):
j += 1
letter += [i.split('/')]
for k in range(len(letter[j])):
out += mor.get(letter[j][k], '?')
out += ' '
print('\n >>> Your msg is: ', end = '')
print(''.join(out))`
output:
Enter your msg in Morse.
Notic that:
1- Use / to separate the letters and space to separate words.
2- Your message must contain only letters and numbers.
3- '?' in output means that your input was unknowed.
>>> ...././.-../.-.. .--/---/.-./.-../-.. (for example)
>>> Your msg is: HELLO WORLD
Upvotes: 0
Reputation: 117886
Once you define the mapping in one direction, you can use a dict comprehension to map it the other way
CODE = {'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': '----.'
}
CODE_REVERSED = {value:key for key,value in CODE.items()}
Then you can use join
with a generator expression to perform the translations.
def to_morse(s):
return ' '.join(CODE.get(i.upper()) for i in s)
def from_morse(s):
return ''.join(CODE_REVERSED.get(i) for i in s.split())
>>> to_morse('hello')
'.... . .-.. .-.. ---'
>>> from_morse('.... . .-.. .-.. ---')
'HELLO'
Upvotes: 24