首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Morse代码翻译器

Python Morse代码翻译器
EN

Code Review用户
提问于 2020-08-18 02:43:13
回答 1查看 445关注 0票数 6

在过去的几周里,我一直在自学Python,我对密码学、密码等有着浓厚的兴趣,所以我认为启动Morse代码翻译将会是一个很好的项目。我知道我的变量名可能是不同的,它并不是真正的加密、解密等等。我主要是在寻找关于如何使代码更简洁和更高效的建议。

我认为我最大的问题是不知道如何像通常那样在while循环中处理输入。我遇到的问题是,我无法检查输入是“e”还是“d”,所以它变得非常不可靠。

我知道我可以改进的领域:

  • 添加输入环
  • 如果,elif,其他的动作
  • 使声音成为一个实际的布尔值
  • 为dit和dah找到实际的声音时间,但这并不是真正的代码问题
代码语言:javascript
复制
# 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)
EN

回答 1

Code Review用户

发布于 2020-08-18 12:25:58

通用风格

翻译dict使用关键字和小写字母。考虑用大写字母写常量,并给它们起表现力的名字,如MORSE_CODES = {...}

根据PEP 8,函数应该使用snake_case命名。CamelCase是为类保留的:outputMessageoutput_messagedef Encrypt(...)def encrypt(...)等。

性能

使用Get_Key函数并不是很好的性能,因为它对dict执行线性搜索。只需将翻译分词反转一次,然后使用它:

代码语言:javascript
复制
MORSE_ENCODING = {
    'a': '.-',
    'b': '-...',
    ...
}
MORSE_DECODING = {value: key for key, value in MORSE_ENCODING.items()}

...

        temp = MORSE_DECODING[letter]

处理错误

目前,Encrypt函数无声地跳过所有不可翻译的字符。考虑抛出一个ValueError(),以指示提供了无效的输入:

代码语言:javascript
复制
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换个短语。

Globals

当程序被用作库时,使用像outputMessage这样的全局变量可能会产生不良的副作用。def Play_Sound函数下面的所有代码都应该进入可以调用的def main()函数。

代码语言:javascript
复制
if __name__ == '__main__':
    main()

在单位的底部。

票数 6
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/248068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档