|
| 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