我正在尝试在python上使用字典和函数。我正在尝试编写一个用加密字母表加密简单短语或句子的程序:
Original alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Encrypted alphabet: TDLOFAGJKRICVPWUXYBEZQSNMH.
用户输入要加密的短语或句子,以便它可以包含大写或小写字母,空格,逗号和句点。但是,输出应该只是带有空格和标点符号的大写字母。
cipher ={"A":"T","a":"T","B":"D","b":"D","C":"L","c":"L","D":"O","d":"O","E":"F","e":"F","F":"A","f":"A","G":"G","g":"G","H":"J","h":"J","I":"K","i":"K","J":"R","j":"R","K":"I","k":"I","L":"C","l":"C","M":"V","m":"V","N":"P","n":"P","O":"W","o":"W","P":"U","p":"U","Q":"X","q":"X","R":"Y","r":"Y","S":"B","s":"B","T":"E","t":"E","U":"Z","u":"Z","V":"Q","v":"Q","W":"S","w":"S","X":"N","x":"N","Y":"M","y":"M","Z":"H","z":"H"}
def encode(str,cipher):
result=""
for c in str:
result = result + cipher[c]
return result
答案 0 :(得分:1)
有时候请求宽恕然后获得许可会更好。您可以删除一半的键:值并用str.upper()替换它们,这样小写字母就成了大字母。如果你调用dict()。get(key)你得到键的值,或者你得到None。如果cipher.get(字符)返回None,则dict和character之间的or运算符将计算字符。
def get_chiper(plaintext):
cipher = {"A": "T", "B": "D", "C": "L", "D": "O", "E": "F",
"F": "A", "G": "G", "H": "J", "I": "K", "J": "R",
"K": "I", "L": "C", "M": "V", "N": "P", "O": "W",
"P": "U", "Q": "X", "R": "Y", "S": "B", "T": "E",
"U": "Z", "V": "Q", "W": "S", "X": "N", "Y": "M",
"Z": "H"}
return "".join(cipher.get(character.upper()) or character
for character in plaintext)
通过反转dict,可以使用相同的功能完成完整的编码和解码。
def encode(plaintext, cipher):
return "".join(cipher.get(character.upper()) or character
for character in plaintext)
def decode(secret, encoding_cipher):
decode_cipher = {value: key for key, value in encoding_cipher.items()}
return encode(secret, decode_cipher)
def main():
cipher = {"A": "T", "B": "D", "C": "L", "D": "O", "E": "F",
"F": "A", "G": "G", "H": "J", "I": "K", "J": "R",
"K": "I", "L": "C", "M": "V", "N": "P", "O": "W",
"P": "U", "Q": "X", "R": "Y", "S": "B", "T": "E",
"U": "Z", "V": "Q", "W": "S", "X": "N", "Y": "M",
"Z": "H"}
plaintext = "hello foo from bar"
secret = encode(plaintext, cipher)
plaintext = decode(secret, cipher)
print(secret, plaintext)
if __name__ == '__main__':
main()
答案 1 :(得分:0)
您应该排除那些带有未知符号的案例,可以通过以下方式完成:
cipher ={"A":"T","a":"T","B":"D","b":"D","C":"L","c":"L","D":"O","d":"O","E":"F","e":"F","F":"A","f":"A","G":"G","g":"G","H":"J","h":"J","I":"K","i":"K","J":"R","j":"R","K":"I","k":"I","L":"C","l":"C","M":"V","m":"V","N":"P","n":"P","O":"W","o":"W","P":"U","p":"U","Q":"X","q":"X","R":"Y","r":"Y","S":"B","s":"B","T":"E","t":"E","U":"Z","u":"Z","V":"Q","v":"Q","W":"S","w":"S","X":"N","x":"N","Y":"M","y":"M","Z":"H","z":"H"}
def encode(words, cipher):
result = ''
for letter in words:
if letter in cipher:
result = result + cipher[letter]
else:
result = result + letter
return result
phrase = raw_input('Please enter your phrase: ')
print encode(phrase, cipher)