|
| 1 | +import os |
| 2 | + |
| 3 | +# Plain text to morse code dictionary. |
| 4 | +MORSE_CODE_DICT = {'A': '.-', 'B': '-...', |
| 5 | + 'C': '-.-.', 'D': '-..', 'E': '.', |
| 6 | + 'F': '..-.', 'G': '--.', 'H': '....', |
| 7 | + 'I': '..', 'J': '.---', 'K': '-.-', |
| 8 | + 'L': '.-..', 'M': '--', 'N': '-.', |
| 9 | + 'O': '---', 'P': '.--.', 'Q': '--.-', |
| 10 | + 'R': '.-.', 'S': '...', 'T': '-', |
| 11 | + 'U': '..-', 'V': '...-', 'W': '.--', |
| 12 | + 'X': '-..-', 'Y': '-.--', 'Z': '--..', |
| 13 | + '1': '.----', '2': '..---', '3': '...--', |
| 14 | + '4': '....-', '5': '.....', '6': '-....', |
| 15 | + '7': '--...', '8': '---..', '9': '----.', |
| 16 | + '0': '-----', ',': '--..--', '.': '.-.-.-', |
| 17 | + '?': '..--..', '/': '-..-.', '-': '-....-', |
| 18 | + '(': '-.--.', ')': '-.--.-', ' ': '/'} |
| 19 | + |
| 20 | +# Morse code to plain text dictionary. |
| 21 | +REV_MORSE_CODE_DICT = {v: k for k, v in MORSE_CODE_DICT.items()} |
| 22 | + |
| 23 | + |
| 24 | +def translate(text): |
| 25 | + if not all(t == '.' or t == '-' or t == '/' or t.isspace() for t in text): |
| 26 | + print() |
| 27 | + print("The morse code encryption of the text is :-") |
| 28 | + print() |
| 29 | + return ' '.join([MORSE_CODE_DICT.get(t, '?') for t in text]) |
| 30 | + else: |
| 31 | + print() |
| 32 | + print("The translated text is :-") |
| 33 | + print() |
| 34 | + return ''.join([REV_MORSE_CODE_DICT.get(t, '?') |
| 35 | + for t in text.split()]) |
| 36 | + |
| 37 | + |
| 38 | +if __name__ == "__main__": |
| 39 | + os.system('cls') |
| 40 | + print("-" * 50) |
| 41 | + print("ENTER MORSE CODE SENTENCE TO DECODE AND NORMAL SENTENCE TO ENCODE") |
| 42 | + print("-" * 50) |
| 43 | + quit = False |
| 44 | + |
| 45 | + while not quit: |
| 46 | + print() |
| 47 | + user_input = input("Enter a sentence: ") |
| 48 | + print(translate(user_input.upper())) |
| 49 | + print() |
| 50 | + q = input( |
| 51 | + "Do you want another translation ? (Y/Yes) or (N/No): " |
| 52 | + ).lower() |
| 53 | + if q == 'n' or q == 'no': |
| 54 | + quit = True |
| 55 | + |
| 56 | +# Script by Swaraj Baral (github.com/SwarajBaral) |
0 commit comments