python 翻译字符串,并使用字典将其改回

python translating strings, and changing them back using dictionary

我有这段代码可以使用字典翻译一个字符串(开始时是一个列表)。我想让代码翻译字符串,然后将其反译回原始内容。

这是我目前得到的代码:

words = ['Abra', ' ', 'cadabra', '!']
clues = {'A':'Z', 'a':'z', 'b':'y', 'c':'x'}
def converter(words, clues):
    words = ''.join(words)
    for item in words:
        if item in clues.keys():
            words = words.replace(item, clues[item])
    return words
def reversal(clues):
    clues = {v: k for k, v in clues.items()}
    print(clues)
x = converter(words, clues)
print(x)
reversal(clues)
x = converter(words, clues)
print(x)

只有,这会打印 "Zyrz xzdzyrz!" "Zyrz xdzyrz!" 我不确定为什么它不打印: "Zyrz xzdzyrz!" "Abra cadabra!"

我的代码中是否有错误导致它以这种方式运行?我检查了线索,它在通过函数后被正确地反转了。我做错了什么?

看起来您正在尝试在函数中就地执行字典操作。您的函数需要 return 字典的反向版本,然后您需要在主函数中获取该字典:

# Your stuff here

def reversal(clues):
    return {v: k for k, v in clues.items()}

x = converter(words, clues)
print(x)
clues_reversed = reversal(clues)
x = converter(words, clues_reversed)
print(x)

Python 已经有所有字符串的 translate 方法,调用它即可!

def converter(text, clues, reverse=False):
    if reverse:
        clues = {v: k for k, v in clues.items()}
    table = str.maketrans(clues)
    return text.translate(table)

用法:

words = ['Abra', ' ', 'cadabra', '!']
clues = {'A':'Z', 'a':'z', 'b':'y', 'c':'x'}

# join the text into a single string:
x = ''.join(words)

# convert first
x = converter(x, clues)
print(x) # -> you get `Zyrz xzdzyrz!`

#back to original
x = converter(x, clues, reverse=True) 
print(x) # -> you get `Abra cadabra!`