-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathmorse_codepy.py
63 lines (51 loc) · 2.06 KB
/
morse_codepy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from data import morse_code
class MorseCode:
def __init__(self):
self.in_morse = ""
self.in_english = ""
def to_morse(self, sentence):
'''
Takes one required parameter sentence of type string and
converts it into the equivalent morse code.
'''
self.in_morse = ""
sentence = sentence.split(" ")
# print(sentence)
morse_translation = []
for word in sentence:
# Converting each word to a list of characters
word_ = list(word)
# Matching every character with morse code in data.py
for letter in word_:
morse_translation.append(morse_code[letter.lower()])
# Adding a forwars slash at end of each word except the last word
if sentence.index(word) != len(sentence)-1:
morse_translation.append("/")
# Joining the final list to make a string of morse code characters
self.in_morse = " ".join(morse_translation)
return self.in_morse
def to_english(self, code_in_morse):
'''
Converts morse code to english takes one required parameter
code_in_morse as a string
'''
self.in_english = ""
# Checking if the entered code has "/" as seperator or not?
if "/" in code_in_morse:
code_list = code_in_morse.split(" / ")
else:
code_list = code_in_morse.split(" ")
# Creating a list for morse code to convert it later to english
morse_list = []
for code in code_list:
code = code.split(" ")
morse_list.append(code)
# Looping through the dictionary of morse code and replacing morse to letter
for word in morse_list:
for letter in word:
for key, value in morse_code.items():
if letter == value:
self.in_english += key
# After each word concatinating the white space
self.in_english += " "
return self.