UnboundLocalError (Локальная переменная, на которую ссылаются до назначения) Django - PullRequest
0 голосов
/ 19 января 2020

Для этой функции я собираюсь расшифровать строку кода Морзе обратно к предложению. Но ошибка выдает следующее: UnboundLocalError (локальная переменная «пробел», на которую ссылаются перед присваиванием)

Я исследовал в Интернете, люди используют global для решения проблемы, но это не работает на меня, и я делаю это только локально, поэтому я не хочу, чтобы это повлияло на мой код позже.

Вот мой взгляд:

def decipher(request):
    """The Decipher Page"""
    MORSE_CODE_DICT = {'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': '-----', ', ': '--..--', '.': '.-.-.-',
                       '?': '..--..', '/': '-..-.', '-': '-....-',
                       '(': '-.--.', ')': '-.--.-'}

    def decrypt(message):
        # extra space added at the end to access the
        # last morse code
        message += ' '
        decipherMsg = ''
        citext = ''
        for letter in message:
            # checks for space
            if letter != ' ':
                # counter to keep track of space
                space = 0
                # storing morse code of a single character
                citext += letter
                # in case of space
            else:
                # if i = 1 that indicates a new character
                space += 1
                # if i = 2 that indicates a new word
                if space == 2:
                    # adding space to separate words
                    decipherMsg += ' '
                else:
                    # accessing the keys using their values (reverse of encryption)
                    decipherMsg += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(citext)]
                    citext = ''
        return decipherMsg

    val1 = request.GET.get('a1', '')
    res = decrypt(val1)

    return render(request, 'morse_logs/decipher.html', {'result': res})

Мой html:

{% block content %}
<h1>Decipher</h1>
    <form action="" method="get" >
        <textarea rows="10" cols="50" name='a1' ></textarea>
        <textarea rows="10" cols="50" name='a2' > {{result}} </textarea>
        <button type="submit" name="cipher">Cipher</button>


        {% comment %}
        <textarea rows="10" cols="50" name="a3" > {{result}} </textarea>
        {% endcomment %}
    </form>
{% endblock content  %}

1 Ответ

1 голос
/ 19 января 2020

Причина, по которой это происходит, заключается в том, что вы используете переменную space, прежде чем присваивать ей значение. Это может произойти, если первым символом сообщения является, например, пробел.

Кроме того, лучше создать словарь, который отображается в обратном порядке, и проверить, что citext содержит хотя бы один символ:

MORSE_CODE_DICT_REV = {v: k for k, v in MORSE_CODE_DICT.items()}

def decrypt(message):
        # extra space added at the end to access the
        # last morse code
        message += ' '
        decipherMsg = ''
        citext = ''
        <b>space = 0</b>
        for letter in message:
            # checks for space
            if letter != ' ':
                # counter to keep track of space
                space = 0
                # storing morse code of a single character
                citext += letter
                # in case of space
            else:
                # if i = 1 that indicates a new character
                space += 1
                # if i = 2 that indicates a new word
                if space == 2:
                    # adding space to separate words
                    decipherMsg += ' '
                elif <b>citext != ''</b>:
                    # accessing the keys using their values (reverse of encryption)
                    decipherMsg += MORSE_CODE_DICT_REV[citext]
                    citext = ''
        return decipherMsg
...