"有没有一种方法可以用字典中带有字母值的数字来解密一条句子?"

2024-10-03 19:32:33 发布

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

我需要“翻译”一个用数字写的句子(比如“112233”),用一个字典给一个字母指定两个数字

这就是字典:

code_2 = {14: 'a', 15: 'b', 16: 'c', 24: 'd', 25: 'e', 26: 'f', 34: 'g', 35: 
'h', 36: 'i', 44: 'j', 45: 'k', 46: 'l',
 54: 'm', 55: 'n', 56: 'ñ', 64: 'o', 65: 'p', 66: 'q', 74: 'r', 75: 's',
 76: 't', 84: 'u', 85: 'v', 86: 'w', 94: 'x', 95: 'y', 96: 'z'}

我试着每两个数字分开一个给定的句子(比如141516),所以它返回这个:14 15 16 我的目标是能够将一个用数字写的代码翻译成一个带字母的句子,例如,如果有人写“3525464664”,我希望程序使用上面的字典(“hello”)返回它的翻译

这就是我找到的函数

def codification(words,code_2):

    result=''

    for letter in words:

        if letter in code_2:

            result= result+str(code_2[letter])

        else:

            result= result+letter

    return result


sentence= input('Write:')


print (str(codification(sentence,code_2)))

我还找到了一种方法,用以下代码将一系列数字分成两个数字的组:

def encrypt(code, lenght):


    return ' '.join(code[i:i+lenght] for i in range(0,len(code),lenght))



code= input()



print(encrypt(str(code),2))

我不知道如何解决这个问题,所以如果有人能帮助我,我将非常感激

[编辑]:有没有办法翻译两个或更多的单词?例如,“3525464664 267436255524”(“你好,朋友”)。因为在下面给出的代码中,如果我尝试这样做,会收到一条错误消息。


Tags: 代码infor字典def字母code数字
1条回答
网友
1楼 · 发布于 2024-10-03 19:32:33

您可以尝试以下操作:

  1. 将字符串拆分为两个数字的列表(假定code_2中的键总是两位数的数字)。你知道吗
  2. 迭代上一个列表并选择code_2中的值。你知道吗

同样,我使用"".join(my_list)方法将list转换为string。一些解释here

# Your dict
code_2 = {14: 'a', 15: 'b', 16: 'c', 24: 'd', 25: 'e', 26: 'f', 34: 'g',
         35:'h', 36: 'i', 44: 'j', 45: 'k', 46: 'l', 54: 'm', 55: 'n',
         56: 'ñ', 64: 'o', 65: 'p', 66: 'q', 74: 'r', 75: 's', 76: 't',
         84: 'u', 85: 'v', 86: 'w', 94: 'x', 95: 'y', 96: 'z'}


def decode_word(text):
    # Split to a list of 2 numbers
    text_l = ["".join([a,b]) for a,b in zip(text[::2], text[1::2])]

    # Rebuild the world
    return "".join([code_2[int(key)] for key in text_l])


print(decode_word("3525464664"))
# hello

如果要使其更安全,可以使用:

def decode_word(text):
    # Check then length or the string
    if len(text) %2 != 0:
        raise ValueError("Text incorrect (must have a even length)")

    # Split to a list of 2 numbers
    text_l = ["".join([a,b]) for a,b in zip(text[::2], text[1::2])]

    # Rebuild the world
    word = "".join([code_2.get(int(key), "") for key in text_l])

    # Check if all keys have been found
    if len(word) < len(text)//2:
        print("WARNING: Some keys doesn't belong to 'code_2'.")
    return word

相关问题 更多 >