用词典翻译

2024-10-04 01:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是试着从练习本上尝试一些代码,有不同的练习,但我想尝试一个有预先存在的信息,我已经做了这么多,但我不知道如何完成它。我该怎么做呢?在

alphabet = {"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": "--.."}

message = ".-- .... . .-. . / .- .-. . / -.-- --- ..-"

for key,val in alphabet.items():
    if message in alphabet:
        print(key)

Tags: key代码in信息messageforifitems
2条回答

你需要把字典倒过来:

alphabet1 = {b:a for a, b in alphabet.items()} 
message = ".  .... . .-. . / .- .-. . / -.   - ..-"
decoded_message = ''.join(alphabet1.get(i, ' ') for i in message.split())

输出:

^{pr2}$

这里的基本问题是,您需要将消息拆分为可以单独解码的单独部分。在

消息首先用斜杠(单词)分隔,然后用空格(字符)分隔。因此我们可以在这里使用split()两次来获得元素:

for word in message.split('/'):
    for character in word.strip().split():
        # ... decode the character

现在我们需要一些东西来解码这个角色。但是用字符作为键存储字典没有多大意义:我们想要解码消息,所以这里的点和连字符需要是键,而不是字母表字符。在

我们可以自己创建新词典,也可以自动创建新词典:

^{pr2}$

因此,我们可以使用查找方法:

decode_dict = {v: k for k, v in alphabet.items()}

for word in message.split('/'):
    for character in word.strip().split():
        print(decode_dict[character])  # print the decoded character
    print(' ')  # print space after the word

现在我们得到解码后的消息,但是每个字符都在一行。但是,我们可以先使用str.join和生成器生成字符串:

' '.join(''.join(decode_dict[character] for character in word.strip().split())
         for word in message.split('/'))

结果就是解码后的字符串:

>>> ' '.join(''.join(decode_dict[character] for character in word.strip().split())
...          for word in message.split('/'))
'WHERE ARE YOU'

相关问题 更多 >