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

时间:2018-10-17 18:05:48

标签: python string dictionary translate

我有这段代码可以使用字典翻译字符串(以列表开头)。我希望代码转换字符串,然后将其取消转换回原始字符串。

这是到目前为止我得到的代码:

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!” “阿布拉·卡达布拉!”

我的代码中是否有错误导致其以这种方式运行?我检查了线索,并在通过该功能后将其正确反转。我在做什么错了?

2 个答案:

答案 0 :(得分:0)

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!`

答案 1 :(得分:-1)

似乎您正在尝试在函数中进行字典操作。您的函数需要返回字典的反向版本,然后您需要在主目录中获取它:

# 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)