到目前为止,这是我的代码 基本上我需要做的是创建一个基于加密和解密的程序,可以打开和编码/解码文件,然后保存解密/加密的消息。正如您所看到的,我使用了一个关键字Caesar cipher,它将改变消息。但是,我对python相对较新,对如何保存编码或解码的消息或如何打开消息进行编码/解码知之甚少。真的很感激帮助。
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
file=input("enter file name (dont write .txt)")
f = open (file+'.txt','r')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % 26)
key = int(input())
if (key >= 1 and key <= 26):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
getMode()
getMessage()
getKey()
getTranslatedMessage(mode, message, key)
getTranslatedMessage(mode, message, key)
答案 0 :(得分:1)
您应该查看getMessage()函数。它实际上并没有返回文件的内容。
按如下方式更改getMessage()使其正常工作。
def getMessage():
file=input("enter file name (dont write .txt)")
with open(file+'.txt', 'r') as text_file:
read_data = text_file.read()
return read_data