Pythonモールス信号翻訳
私はここ数週間Pythonを自分で学んでいて、暗号化やコードなどに興味があるので、モールス信号の翻訳者を始めるのは良いプロジェクトだと思いました。変数名が異なる可能性があることはわかっていますが、実際には暗号化や復号化などではありません。コードをよりクリーンにする方法と、より効率的にする方法についてのアドバイスを主に探しています。
私の最大の問題は、通常のようにwhileループで入力を処理する方法を実際に知らないことだと思います。私が抱えていた問題は、入力が「e」か「d」かを確認できなかったため、本当に不安定になったということでした。
改善できるとわかっている領域:
- 入力ループを追加する
- アクションのif、elif、else
- 'sound'を実際のブール値にする
- 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()
代わりにスローして、無効な入力が提供されたことを示すことを検討してください。
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()
ユニットの下部にあります。