In one of my previous post, I’ve designed a simple Morse Code Decoder in Python which is capable of accepting user inputs and outputting them in their original alphanumerical form. One of the limitations of the decoder is that it does not allow the user to input sentences. Remember that we have chosen to represent each alphabet or number using a series of ‘0’ and ‘1’, where ‘0’ represents a dot, and ‘1’ represents a dash. Each alphabet or number is then separated by a ‘*’ in our decoder, as shown in the screenshot below.
In this post, we will improve our simple Morse Code Decoder to be able to decipher sentences as well. Furthermore, we can implement checks in the decoder to inform us of the frequencies in which each alphabet/number, word, or sentence type have been decoded.
One major difference between this decoder and the previous one is that we will be using Python class to build our decoder and the respective analysis checks. A simple explanation about Python class is that it defines a set of _instance variables _(data values to be represented for each object) and a set of _methods _(operations) that can be applied to the objects.
We will build a class called **Decoder **and it will contain several methods, with the first being init(self). This is the essential method for object creation and it usually initialize the values of the instance variables of each object. Remember that we chose to use a dictionary structure to store our Morse Code representation in Python, where each alphabet or number is represented by a series of ‘0’s and ‘1’s. As we are adding sentences analysis checks too, we have also added three punctuation marks “ _. _” , “ _, _” and “ _? _”.
class Decoder:
def __init__(self):
self.the_dict = dict(zip(('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','.',',','?'),('01','1000','1010','100','0','0010','110','0000','00','0111','101','0100','11','10','111','0110','1101','010','000','1','001','0001','011','1001','1011','1100','11111','01111','00111','00011','00001','00000','10000','11000','11100','11110','010101','110011','001100')))
The next essential method in a class creation is returning/printing the output. With just the init **(self) **method, we cannot display any results if we assign a variable to this class. We will add a str **(self) **method which works the same way as **print(variable), **but allows us to customize the way the results will be displayed.
def __str__ (self):
dict_str = ""
for key,value in self.the_dict.items():
dict_str += "Character: " + str(key) + " ->" + " Code: " + str(value) + "\n"
return dict_str
#data-science #object-oriented #data-analysis #python #morse-code