파이썬 모스 부호 번역기
저는 지난 몇 주 동안 파이썬을 스스로 가르치고 있었고 암호화, 코드 등에 관심이있어서 모스 코드 번역기를 시작하는 것이 좋은 프로젝트가 될 것이라고 생각했습니다. 내 변수 이름이 다를 수 있다는 것을 알고 있습니다. 실제로 암호화, 복호화 등이 아닙니다. 주로 코드를 더 깔끔하게 만들 수있는 방법과 더 효율적일 수있는 부분에 대한 조언을 찾고 있습니다.
내 가장 큰 문제는 평소처럼 while 루프에서 입력을 처리하는 방법을 실제로 알지 못한다는 것입니다. 내가 가진 문제는 입력이 'e'인지 'd'인지 확인할 수 없어서 정말 이상해졌습니다.
내가 개선 할 수있는 부분 :
- 입력 루프 추가
- 액션에 대한 if, elif, else
- '사운드'를 실제 부울 값으로 만듭니다.
- dit 및 dah에 대한 실제 사운드 시간을 찾으십시오.하지만 실제로는 코드 문제가 아닙니다.
# Started: 08/17/2020
# Finished: 08/17/2020
# Takes an input message and outputs the message in morse code
# Keys taken from 'https://en.wikipedia.org/wiki/Morse_code'
from playsound import playsound
import time
# Dictionary that holds each letter and it's corresponding value
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': '-----',
' ': '/', '.': '.-.-.-', ',': '.-.-', '?': '..--..', "'": '.----.', '!': '-.-.--', '/': '-..-.', '(': '-.--.', ')': '-.--.-',
':': '---...', ';': '-.-.-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '_': '..--.-', '"': '.-..-.', '$': '...-..-', '@': '.--.-.'}
outputMessage = "" # Holds our output message
# Sounds
sound = 'False'
dit = 'dit.wav'
dah = 'dah.wav'
def Encrypt(message):
output = ''
for char in message:
if char in dict:
output = output + dict[char]
output = output + ' '
return output
def Get_Key(val):
for key, value in dict.items():
if val == value:
return key
def Decrypt(message):
output = ''
letters = message.split(' ')
for letter in letters:
temp = Get_Key(letter)
output = output + temp
return output
def Get_Inputs():
# Get Inputs
inputString = input('Enter a message to start.\n')
action = input('(E)ncrypt or (D)ecrypt?\n')
# Format Inputs
message = inputString.lower().strip()
action = action.lower().strip()
return message, action
def Play_Sound(message):
for char in message:
if char == '.':
playsound(dit)
elif char == '-':
playsound(dah)
elif char == ' ':
time.sleep(0.15)
elif char == '/':
time.sleep(0.30)
message, action = Get_Inputs()
if action == 'e' or action == 'encrypt':
outputMessage = Encrypt(message)
elif action == 'd' or action == 'decrypt':
outputMessage = Decrypt(message)
else:
print('Error!')
print(outputMessage)
print('')
sound = input('Play sound? (T)rue / (F)alse\n')
if sound.lower().strip() == 't' or sound.lower().strip() == 'true':
Play_Sound(outputMessage)
답변
일반 스타일
번역 dict
은 키워드와 소문자를 사용합니다. 대문자로 상수를 작성하고 MORSE_CODES = {...}
.
PEP 8 에 따르면 함수 이름은 snake_case
. CamelCase
수업 용으로 예약되어 있습니다 : outputMessage
→ output_message
, def Encrypt(...)
→ def encrypt(...)
등
공연
Get_Key
함수를 사용하는 것은 dict의 선형 검색을 수행하기 때문에 성능이 좋지 않습니다. 번역 사전을 한 번 뒤집은 다음 사용하십시오.
MORSE_ENCODING = {
'a': '.-',
'b': '-...',
...
}
MORSE_DECODING = {value: key for key, value in MORSE_ENCODING.items()}
...
temp = MORSE_DECODING[letter]
오류 처리
현재이 Encrypt
함수는 번역 할 수없는 모든 문자를 자동으로 건너 뜁니다. ValueError()
대신 Throwing a 를 고려하여 잘못된 입력이 제공되었음을 나타냅니다.
def encode(message):
"""Encodes a string into morse code."""
code = ''
for index, char in enumerate(message):
try:
code += MORSE_ENCODING[char.lower()]
except KeyError:
raise ValueError(f'Char "{char}" at {index} cannot be encoded.')
code += ' '
return code[:-1] # Remove trailing space.
def decode(morse_code):
"""Decodes morse code."""
message = ''
for index, sequence in enumerate(morse_code.split()):
try:
message += MORSE_DECODING[sequence]
except KeyError:
raise ValueError(f'Cannot decode code "{sequence}" at {index}.')
return message
단정
귀하의 Encrypt
기능은 현재 항상 후행 공백을 반환합니다. 을 반환하면이를 피할 수 있습니다 output[:-1]
.
술어
모스 부호에서 텍스트로 앞뒤로 변환하는 것은 그 의미에서 실제로 암호화가 아닙니다. 당신은 바꿔 할 수 있습니다 {en,de}crypt
로 {en,de}code
.
글로벌
같은 전역 변수를 사용 outputMessage
하면 프로그램이 라이브러리로 사용될 때 불쾌한 부작용이 발생할 수 있습니다. def Play_Sound
함수 아래의 모든 코드는 다음을 def main()
통해 호출 할 수 있는 함수 로 이동해야합니다.
if __name__ == '__main__':
main()
장치 하단에 있습니다.