Python Caesar Cypher 分析输入文件

Python Caesar Cypher analysing an input file

我正在尝试创建一个 Caesar Cypher 函数,当给定一个输入文件时,程序(通过命令行)分析该文件,找出每个字母(小写和大写)的数量。从那里我可以找出解密文件的密钥。

我遇到的问题是提取最常见的字母,然后我可以将其转换为密钥。

我下面的代码远未完成。我一直在努力寻找一种方法来提取最常见的字母。从那里我相信使用已经使用的代码变体我将能够转换和使用数字作为密钥。我真的只需要一个关于如何获取初始字符的指针。

这段代码不是完整的程序,只是用来分析文件并将结果存储在字典中的代码:

elif fileOption == "2":
def decryptChars(aString):
    "Function to count characters in the input file"
    charCount = {}
    for char in aString:
        if char in charCount.isalpha():
            if char in charCount:
                charCount[char] = charCount[char] + 1
            else:
                charCount[char] = 1
        return charCount

try:
    inputFile = open(sys.argv[1], "r")
except:
    sys.exit("The file {} could not be opened...".format(sys.argv[1]))

totalChars = inputFile.read().replace(" ", "")

charCount = decryptChars(totalChars)
print(sorted(charCount.items()))

当我传递一个带有字符串 "Rather than requiring all the desired functionality to be built into the language's core" 的文件时,我得到的结果是:

[('R', 1), ('a', 6), ('b', 2), ('c', 2), ('d', 2), ('e', 9), ('f', 1), ('g', 3), ('h', 4), ('i', 7), ('l', 5), ('n', 6), ('o', 4), ('q', 1), ('r', 5), ('s', 2), ('t', 9), ('u', 4), ('y', 1)]

(我不知道最好的测试片,因为它会 return 2 和 9...)。

任何建议都会非常有帮助。

好的,鉴于您的列表包含以下对:

l = [('R', 1), ('a', 6), ...]

最简单的方法是使用 for 循环

char = ''
freq = 0
for new_char, new_freq in l:
    if new_freq > freq:
        freq = new_freq
        char = new_char

假设:

charCount = {'R': 1, 'a': 6, 'b': 2...}

这是获取出现次数最多的字符的一行代码:

max(charCount, key=charCount.get)