找出字母python之间的区别

时间:2016-11-24 14:37:40

标签: python frequency caesar-cipher

已经完成任务并且差不多完成了。刚刚与最后一点挣扎。该程序被赋予一个凯撒密文,然后计算出最常见的字母是什么,并将其打印回终端。 (我在哪里。) 然后它会建议基于最常用字母的键移位,然后用户可以手动输入此键移位,或者他们自己的键移位,文本被解密。

我需要该程序在凯撒文本中使用最常用的字母,并将其与字母“E'”进行比较。这是英语中最常用的字母,然后计算出它有多少关键的转变......

e.g。如果最常见的凯撒文本字母是n,那么n-e = 9。

到目前为止

代码:

    import sys 

def decrypt(plain, key):
"returns a Caesar cipher text given plain text and a key"
   cipher = ""
for index in range(len(plain)):
 if plain[index].isalpha():    
   if plain[index].islower():
    cipher = cipher + chr((ord(plain[index]) -101- key+26) % 26+ 101)
   else:
    cipher = cipher + chr((ord(plain[index]) -65- key+26) % 26+ 65)
 else:
   cipher = cipher + plain[index]


  return cipher            #do nothing here 

  #main program 

key = int(sys.argv[4])
action = sys.argv[2]

try:
   in_file = open(sys.argv[1], "r")
except:
sys.exit("There was an error opening the file: {}".format(sys.argv[1]))

 try:
  out_file = open(sys.argv[3], "w")

except:
sys.exit("There was an error opening the file: {}".format(sys.argv[3]))

line = in_file.readline()

freq_dict = { }#letter : 0 for letter in LETTERS }



while len(line) != 0:
for letter in line.replace(" ",""):
    if letter in freq_dict:
        freq_dict[letter] += 1
    else:
        freq_dict[letter] = 1 
line = in_file.readline()


cipher = decrypt(line, key)
out_file.write(cipher)



in_file.close()
out_file.close()

for letter in freq_dict:
print(letter, "times", freq_dict[letter])

提前致谢。

1 个答案:

答案 0 :(得分:0)

所以看来你的decrypt函数实际上生成了一个输出,它是现在由键移动的输入文本字符串。

根据我的理解,您当时想要做的是找到此字符串中最常出现的字母。

您可以使用collections模块执行此操作

import collections
most_freq = collections.Counter(cipher).most_common(1)[0]

现在您剩下的就是找到most_freq来信与e之间的转换。

也许最简单的方法就是枚举列表中的字母表,然后找出两者之间的索引差异。

alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

shift = alphabet.index(most_freq) - alphabet.index('e')

请记住,这种转变会使您从e转到most_freq字母,因此当您将班次应用于文字时,您需要应用相反的(-1 * shift)来获得正确的结果。

希望这有帮助。