This article is participating in Python Theme Month. See the link to the event for more details

Morse code is a method of transmitting a text message as a series of on-off tones, lights, or clicks that can be translated directly by a memorized companion without special equipment. It was named after Samuel F. B. Morse, the inventor of the telegraph.

algorithm

The algorithm is very simple. Every character in English is replaced by a series of “dots” and “dashes,” or sometimes just a singular “dot” or “dash,” and vice versa.

encryption

  1. In the encrypted case, we take each character (if not Spaces) from the word one at a time and match it to the corresponding Morse password stored in any data structure of our choice (dictionaries can become very useful in this case if you use Python encoding)
  2. We store the Morse password in a variable that will contain the string we encoded, and then we add a space to the string that contains the result.
  3. In Morse code, we need to add one space between each character and two consecutive Spaces between each word.
  4. If the character is a space, add another space to the variable that contains the result. We repeat this process until we have traversed the entire string

decryption

  1. In the case of decryption, we first add a space at the end of the string to be decoded (this will be explained later).
  2. Now we continue to extract characters from the string until we run out of space.
  3. Once we get a space, we look for the corresponding English character in the extracted character sequence (or our Morse code) and add it to the variable that will store the result.
  4. Keep in mind that tracking space is the most important part of this decryption process. Once we have two consecutive Spaces, we add another space to the variable that contains the decoded string.
  5. The last space at the end of the string will help us identify the last sequence of Morse code characters (because the space acts as a check to extract the characters and begin decoding them).

perform

Python provides a data structure called a dictionary, which stores information in key-value pairs, which is handy for implementing passwords such as Morse code. We can store the Morse code table in a dictionary where (key-value pairs) => (English characters – Morse code). Plaintext (English characters) replaces the key, and ciphertext (Morse code) forms the corresponding key value. The value of a key can be accessed from a dictionary, just as we access the value of an array through an index, and vice versa.

Morse code reference table

A Python program that implements Morse code translator
  
'' VARIABLE KEY 'cipher' -> 'stores the Morse translation of English strings '' decipher' ->' stores the Morse translation of English strings '' citext' -> 'Stores the Morse cipher of single characters '' I' -> 'Calculates Spaces between Morse characters '' message' ->' Stores the string to be encoded or decoded ''
  
# represents a dictionary of Morse code diagrams
MORSE_CODE_DICT = { 'A':'-'.'B':'-... '.'C':'-. -..'D':'-.. '.'E':'. '.'F':'.. -. '.'G':'-.'.'H':'....'.'I':'.. '.'J':'-'.'K':'-. -.'L':'.-..'.'M':The '-'.'N':'-'.'O':The '-'.'P':'--.'.'Q':'-. -.'R':'-'.'S':'... '.'T':The '-'.'U':'.. - '.'V':'... - '.'W':'--'.'X':'-.. - '.'Y':'-. -.'Z':'-- -.. '.'1':'--'.'2':'..---'.'3':'... -- '.'4':'... - '.'5':'... '.'6':'-....'.'7':'--...'.'8':'-- -.. '.'9':'-.'.'0':'-- -- -- -- --.', ':'-- -.. -- '.'. ':'-. -. -'.'? ':'.. -.. '.'/':'-.. -. '.The '-':'-... - '.'(':'-. -..') ':'-. -. -'}
  
Function that encrypts a string according to a Morse cipher diagram
def encrypt(message) :
    cipher = ' '
    for letter in message:
        ifletter ! =' ':
  
            Look it up in the dictionary and add the corresponding Morse code
            # Morse code with Spaces separating different characters
            cipher += MORSE_CODE_DICT[letter] + ' '
        else:
            # 1 Spaces for different characters
            # 2 means different words
            cipher += ' '
  
    return cipher
  
Function that decrypts a string from Morse to English
def decrypt(message) :
  
    # Add extra space at the end to access the last Morse code
    message += ' '
  
    decipher = ' '
    citext = ' '
    for letter in message:
  
        # Check space
        if(letter ! =' ') :# counter to track space
            i = 0
  
            # in the case of Spaces
            citext += letter
  
        # in the case of space
        else:
            # If I = 1 indicates a new character
            i += 1
  
            # If I = 2 indicates a new word
            if i == 2 :
  
                 # Add Spaces to separate words
                decipher += ' '
            else:
  
                Use their values to access the keys (the reverse of encryption)
                decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT
                .values()).index(citext)]
                citext = ' '
  
    return decipher
  
# Hardcode the driver function to run the program
def main() :
    message = "JUEJIN-HAIYONG"
    result = encrypt(message.upper())
    print (result)

    message = ". -.. -... -... -. -... -... . -.. -.. -- -- -- -- -- -- --."
    result = decrypt(message)
    print (result)

    message = "I LOVE YOU"
    result = encrypt(message.upper())
    print (result)

    message = ".. . -.. -... -.-.-- ---.. -"
    result = decrypt(message)
    print (result)
   
# Execute the main function
if __name__ == '__main__':
    main()
Copy the code

Output:

. -.. -... -... -. -... -... . -.. -.-- --- -. --. JUEJIN-HAIYONG .. . -.. -... -.-.-- ---.. - I LOVE YOUCopy the code

Quick summary – Python program to implement Morse code translator

That’s all for this article, you use a Python program to implement a Morse cipher translator. We hope this blog has been helpful to you, and the bloggers are still learning, so if there are any mistakes, please criticize and correct them. If you enjoyed this article and are interested in seeing more of it, you can check it out here (Github/Gitee). This is a summary of all my original works and source code. Follow me for more articles.

๐Ÿฅ‡ Python for data visualization series summary

  • Matplotlib for data visualization in Python
  • Seaborn for data visualization in Python
  • Bokeh for data visualization in Python
  • Plotly for data visualization using Python

More on this at ๐Ÿงต

  • 30 Python tutorials and tips
  • Python statements, expressions, and indentation
  • Python keywords, identifiers, and variables
  • How do I write comments and multi-line comments in Python
  • Learn about Python number and type conversions through examples
  • Python data types — from basic to advanced
  • Teach you how to make a snake game in Python
  • Object-oriented programming in Python – objects, objects, and members

๐Ÿฐ Past excellent articles recommended:

  • 20 Python Tricks Everyone must Know
  • 100 Basic Python Interview Questions Part 1 (1-20)
  • 100 Basic Python Interview Questions Part 2 (21-40)
  • 100 Basic Python Interview Questions Part 3 (41-60)
  • 100 Basic Python Interview Questions Part 4 (61-80)
  • 100 Basic Python Interview Questions Part 5 (81-100)

If you do learn something new from this post, like it, bookmark it and share it with your friends. ๐Ÿค— Finally, don’t forget โค or ๐Ÿ“‘ for support