将 secret 消息翻译成真实字母的Python程序

标签 python linux dictionary

我已将这本字典作为 secret 语言,当用户用 secret 语言输入句子时,它应该以真实字母表返回,这是我编写的代码。

secret = {'b' : 'a', 'c' : 'b', 'd' : 'c', 'e' : 'd', 'f' : 'e', 'g' : 'f', 'h' : 'g', 'i' : 'h', 'j' : 'i', 'k' : 'j', 'l' : 'k', 'm' : 'l', 'n' : 'm', 'o' : 'n', 'p' : 'o', 'q' : 'p', 'r' : 'q', 's' : 'r', 't' : 's', 'u' : 't', 'v' : 'u', 'w' : 'v', 'x' : 'w', 'y' : 'x', 'z' : 'y', 'a' : 'z'}

user = raw_input('Please Input A Secret Sentence :')

print (secret[user])

所以我让它工作,但它只在输入 1 个字母时才工作,它不适用于给出此错误的句子:

[student@localhost 1]$ python idk24.py
Please Input A Secret Sentence :aaa
Traceback (most recent call last):
  File "idk24.py", line 5, in <module>
    print (secret[user])
KeyError: 'aaa'

最佳答案

在您的脚本中,您有多个作为字典传递的数字aaa。字典中没有这样的值,因此您的错误。

这是我的建议:

尝试定义一个新变量并使用 for 循环将用户输入拆分为单个字母。将每个单独的字母添加到整个编码句子中并在末尾打印:

secret = {'b' : 'a', 'c' : 'b', 'd' : 'c', 'e' : 'd', 'f' : 'e', 'g' : 'f', 'h' : 'g', 'i' : 'h', 'j' : 'i', 'k' : 'j', 'l' : 'k', 'm' : 'l', 'n' : 'm', 'o' : 'n', 'p' : 'o', 'q' : 'p', 'r' : 'q', 's' : 'r', 't' : 's', 'u' : 't', 'v' : 'u', 'w' : 'v', 'x' : 'w', 'y' : 'x', 'z' : 'y', 'a' : 'z'}

user = raw_input('Please Input A Secret Sentence :')
entire = ""
for i in user:
    entire = entire + secret[i]    

print (entire)

关于将 secret 消息翻译成真实字母的Python程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48844007/

相关文章:

c - Linux环境变量使用非全路径

arrays - "Expected to decode Dictionary<String, Any> but found a string/data instead.",底层错误: nil))

Python : save dictionaries through numpy. 保存

python - 读取stdin时出现Python字数统计MapReduce错误

python - 选择 QListView 中的所有项目并在目录更改时取消选择所有项目

java - 从远程系统提交 mapreduce 作业时出现异常

linux - 如何在 ELB 或 httpd 级别阻止不需要的请求

python - 'while' 循环可以与 try 和 except 一起使用吗?

python - Django、python、mod_wsgi 和 Apache worker

arrays - 字典中的多个参数