【问题标题】:How to iterate over a dictionary and a list simultaneously? [closed]如何同时遍历字典和列表? [关闭]
【发布时间】:2020-12-25 11:43:50
【问题描述】:

我必须“加密”一个文本文件。我必须用字典值替换文本字符。键是字母。例如,如果文本是“Hello”并且在我的字典中是“h”:“a”,“e”:“d”,我想用“adllo”替换“Hello”。我该怎么做?

【问题讨论】:

  • 你试过什么?一种简单的方法是读取每个字符,在字典中查找并将替换值附加到新列表中。
  • 或者您可以即时执行所有这些操作,只需将新创建的字符串与来自字典的替换项连接起来。

标签: python dictionary encryption


【解决方案1】:

你可以使用:

代码

def encrypt(infile, outfile, translation):
    '''
        Encrypts by applying translation map to characters in file infile.
    '''
    # Create translation table
    table = ''.maketrans(translation)
    
    # Apply table to all characters in input file
    # and write to new output file
    with open(infile, "r") as fin, open(outfile, "w") as fout:
        for line in fin:
            fout.write(line.translate(table))
 

测试

# Dictionary containing map of letters to their new values
d = {"H":"a", "e":"d", "l": "k", "o":"n"}

# Encryp filel 'input.txt'
encrypt('input.txt', "output.txt", d)

# Show Result
print(open("output.txt").read())     

输入文件'input.txt:

Hello
World

输出文件'output.txt'(字典d中指定的字母被替换)

adkkn
Wnrkd

【讨论】:

    猜你喜欢
    • 2021-05-20
    • 2020-05-16
    • 1970-01-01
    • 2018-08-22
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    相关资源
    最近更新 更多