Home » Morse Code Converter in Python

Morse Code Converter in Python

by maxguy71

In this code example we create a morse code converter in python

What is Morse Code

Morse code is a method used in telecommunication to encode text characters as standardized sequences of two different signal durations, called dots and dashes, or dits and dahs.

Morse code is named after Samuel Morse, one of the inventors of the telegraph.

International Morse Code encodes the 26 Latin letters a through z, one non-Latin letter, the Arabic numerals, and a small set of punctuation and procedural signals (prosigns). There is no distinction between upper and lower case letters.

Each Morse code symbol is formed by a sequence of dits and dahs.

The dit duration is the basic unit of time measurement in Morse code transmission. The duration of a dah is three times the duration of a dit. Each dit or dah within an encoded character is followed by a period of signal absence, called a space, equal to the dit duration.

The letters of a word are separated by a space of duration equal to three dits, and words are separated by a space equal to seven dits

International Morse code is composed of five elements:

  1. short mark, dot or dit  : “dit duration” is one time unit long
  2. long mark, dash or dah  : three time units long
  3. inter-element gap between the dits and dahs within a character: one dot duration or one unit long
  4. short gap (between letters): three time units long
  5. medium gap (between words): seven time units long

 

Code

def morse(txt):
    '''Morse code encryption and decryption'''
    
    characters = {'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':'--..', ' ':'.....'}
    translation = ''
    
    # Check for . or -
    if txt.startswith('.') or txt.startswith('−'):
        # Swap key/values in characters:
        d_encrypt = dict([(v, k) for k, v in characters.items()])
        # Morse code is separated by empty space chars
        txt = txt.split(' ')
        for x in txt:
            translation += d_encrypt.get(x)
        
    # Decrypt to Morsecode:
    else:
        txt = txt.upper()
        for x in txt:
            translation += characters.get(x) + ' '
    return translation.strip()
	
print(morse('hello world'))
print(morse('.--. -.-- - .... --- -.'))
print(morse('maxpython'))

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More