如何使用字典替换文本中的字母?

How do I replace letters in text using a dictionary?

我有一本这样的字典:

Letters = {'a': 'z', 'b': 'q', 'm':'j'}

我还有一个随机文本块。

如何用字典中的字母替换文本中的字母。因此,将 'a' 切换为 'z',将 'b' 切换为 'q'。

到目前为止我所做的就是返回错误的输出,我想不出任何其他方法:

splitter = text.split()
res = " ".join(Letters.get(i,i) for i  in text.split())
print(res)

您正在遍历 text 中的单词,而不是单词中的字母。

不需要使用text.split()。只需遍历 text 本身即可获取字母。然后使用空字符串加入它们。

res = "".join(Letters.get(i,i) for i  in text)

我们可以做的是遍历字符串中的每个字符,如果没有找到新字符,则添加新字符或原始字符。

text = "my text ba"
letters = {'a': 'z', 'b': 'q', 'm': 'j'}
result = ""

for letter in text: # For each letter in our string,
    result += letters.get(letter, letter) # Either get a new letter, or use the original letter if it is not found.

如果你愿意,你也可以用一条线来做!

text = "my text ba"
letters = {'a': 'z', 'b': 'q', 'm': 'j'}
result = "".join(letters.get(letter, letter) for letter in text)

这有点令人困惑,所以为了分解它,for letter in text,我们 get 要么是新的 letter,要么我们使用(默认)原始的 letter.

您可以查看 dict.get 方法的文档 here

translation_table = str.maketrans({'a': 'z', 'b': 'q', 'm':'j'})
translated = your_text.translate(translation_table)

简洁快速