如何将Python中的一个字母与一个文本/一个替代的字母配对成一个文本/一个文本的符号?

2024-05-03 12:15:40 发布

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

所以对于我的一个任务,我要做一个游戏,让用户用字典对编码的信息进行加密。我需要这个程序来做的是,当用户键入一个字母时,他们必须键入一个符号来配对,然后我需要根据字母将配对替换成10个单词的列表。在

这是(线索)文本文件:
A
M*
百分之

这是名为(words)的编码单词文本文件:

#+/084&"      
#3*#%#+  
8%203:  
,1$&  
!-*%  
.#7&33&
#*#71%  
&-&641'2  
#))85
9&330*

最后,这是他们应该看起来像未编码(已解决):

获得性
年鉴
侮辱
笑话
赞美诗
瞪羚
亚马逊
眉毛
附加
牛皮

这是我目前为止的代码:

^{pr2}$

对于第二(2)种选择,我不需要它来刷新它的自我,因为所做的改变。所以如果用户要配对(F’),我需要程序返回菜单,如果用户选择(2),我基本上需要用用户的字母代替符号。同样在这个列表下,我想要一个由用户所做的所有替换的列表,如果他们删除了配对,那么需要更新,如果他们要回到列表中。如果有人能帮我解决这个问题,我会很感激的。在


Tags: 用户程序信息游戏编码列表键入字典
1条回答
网友
1楼 · 发布于 2024-05-03 12:15:40

我不认为我完全理解你的问题,我也不想只为你做作业,但下面是一个如何编写一个函数的示例,该函数根据字典中的对来替换字符串中的字符:

pairings = {'#':'A',
            '%':'N',
            '*':'M',
        }

def try_substitution(coded_word, pairings):
    # Create an empty list to hold the decoded letters
    decoded_letters = []
    # Loop over each symbol in the word
    for symbol in coded_word:
        # 'try' is a Python keyword for catching 'exceptions',
        # which are errors that can happen in your code.
        try:
            # Look up this symbol in the pairings dictionary
            decoded_letter = pairings[symbol]
        # KeyError is the exception that happens when you try
        # to look up something that doesn't exist in a dictionary.
        except KeyError:
            # We handle this error case by just keeping the original
            # coded symbol.
            decoded_letters.append(symbol)
        # 'else' means no exception was triggered.
        else:
            # So we can add the decoded letter to our list.
            decoded_letters.append(decoded_letter)
    # Now we join all the decoded letters together.
    # this uses '' (empty string) because we don't want
    # anything separating these letters.
    decoded_word = ''.join(decoded_letters)
    # And return our completed word from the function
    return decoded_word

上面定义了一个字典,它基于“线索”文件将符号映射到字母,并定义了一个接受两个参数的函数:一个编码单词和一个替换字典。在

如果对其中一个编码字调用该函数:

^{pr2}$

你会得到你的单词的部分解码版本。在

编写上面的函数的一种更简短、更花哨的方法是使用Python's generator expressions,但这是一个更高级的功能,如果您只是学习编程或只是学习Python,则不太容易理解:

def try_substitution(coded_word, pairings):
    return ''.join(pairings.get(symbol, symbol) for symbol in coded_word)

我认为,如果您对第一个示例进行修改以理解第一个示例,并对代码进行一些更改,您应该能够得到一个工作程序。在

相关问题 更多 >