Skip to content

Commit 211d841

Browse files
committed
Added Morse Code Translator script
1 parent 4897097 commit 211d841

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

Morse Code Translator/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<div align="center">
2+
3+
# Morse Code Translator
4+
5+
</div>
6+
7+
### Description:
8+
This Python script translates text into Morse code and vice versa.
9+
10+
### How to Use:
11+
1. Run the script in a Python environment.
12+
2. Enter '1' to convert text to Morse code or '2' to convert Morse code to text.
13+
3. Follow the prompts to enter the text or Morse code.
14+
4. The script will perform the conversion and display the result.
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
MORSE_CODE_DICT = {
2+
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---',
3+
'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-',
4+
'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..',
5+
'1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----',
6+
}
7+
8+
9+
def text_to_morse(text):
10+
morse_code = ''
11+
for char in text.upper():
12+
if char == ' ':
13+
morse_code += ' '
14+
else:
15+
morse_code += MORSE_CODE_DICT[char] + ' '
16+
return morse_code
17+
18+
19+
def morse_to_text(morse_code):
20+
text = ''
21+
morse_code += ' '
22+
char = ''
23+
for symbol in morse_code:
24+
if symbol != ' ':
25+
i = 0
26+
char += symbol
27+
else:
28+
i += 1
29+
if i == 2:
30+
text += ' '
31+
else:
32+
text += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(char)]
33+
char = ''
34+
return text
35+
36+
37+
def main():
38+
choice = input("Enter '1' to convert text to Morse code or '2' to convert Morse code to text: ")
39+
if choice == '1':
40+
text = input("Enter the text to convert to Morse code: ")
41+
morse_code = text_to_morse(text)
42+
print("Morse code:", morse_code)
43+
elif choice == '2':
44+
morse_code = input("Enter the Morse code to convert to text (use '.' for dot and '-' for dash): ")
45+
text = morse_to_text(morse_code)
46+
print("Text:", text)
47+
else:
48+
print("Invalid choice!")
49+
50+
51+
if __name__ == "__main__":
52+
main()

0 commit comments

Comments
 (0)