User:Kiken/Construction Site/Implementations/morse code

From Esolang
Jump to navigation Jump to search
from sys import argv

# assuming file is in main.py, execute with: python3 main.py [filename]

def morse_code(code):
    yield_ = code
    index = 0

    morsetochar = {'.-': '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', '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0', '.-.-.-': '.', '--..--': ',', '..--..': '?', '': ''}

    while yield_:
        if index+1 <= len(code) and len(code) >= 1:
            if code[index] == '.':
                if code[index+1] == '.': 
                    yield_ = yield_[1:yield_.index('-')] + '.' + yield_[yield_.index('-'):]
                elif code[index+1] == '-':
                    yield_ = yield_[1:yield_.index('.')] + '-' + yield_[yield_.index('.'):]
                else:
                    yield_ = yield_[1:]
                continue
            elif code[index] == '-':
                if code[index+1] == '.':
                    yield_ = yield_[1] + '-' + yield_[1:]
                elif code[index+1] == '-':
                    yield_ = yield_[0] + yield_[2:]
                    yield_ = yield_[:3] + yield_[0] + yield_[3:]
                else:
                    yield_ = yield_[1:]
                continue
            else:
                break
        else:
            break
        index += 1

    english_plain_text = ''
    morse_code = yield_

    current_char_morse_code = ''
    i = 0

    while i < len(morse_code) - 1:
        if morse_code[i] == ' ':
            if len(current_char_morse_code) == 0 and morse_code[i + 1] == ' ':
                english_plain_text += ' '
                i += 1
            else:
                english_plain_text += morsetochar[current_char_morse_code]
                current_char_morse_code = ''
        else:
            current_char_morse_code += morse_code[i]

        i += 1

    if len(current_char_morse_code) > 0:
        try:
            english_plain_text += morsetochar[current_char_morse_code]
        except KeyError:
            english_plain_text += '#'

    return english_plain_text

with open(argv[1]) as f:
    print(morse_code(f.read()))