在过去的几周里,我一直在自学Python,我对密码学、密码等有着浓厚的兴趣,所以我认为启动Morse代码翻译将会是一个很好的项目。我知道我的变量名可能是不同的,它并不是真正的加密、解密等等。我主要是在寻找关于如何使代码更简洁和更高效的建议。
我认为我最大的问题是不知道如何像通常那样在while循环中处理输入。我遇到的问题是,我无法检查输入是“e”还是“d”,所以它变得非常不可靠。
我知道我可以改进的领域:
# 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)发布于 2020-08-18 12:25:58
翻译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(),以指示提供了无效的输入:
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()在单位的底部。
https://codereview.stackexchange.com/questions/248068
复制相似问题