2017-02-18 54 views
1

我的任务是提供一个能够解密Cesar密码的程序,并且我正在查看以前在本站上提出的其他问题,并且大部分都了解它。但是,我只是有一个关于如何获得字符串中每个字母的基本问题。如何获取字符串中每个字母的计数?

这里就是我想出迄今:

Input=input("input the text you want to decipher:") 

import string 
print(string.ascii_uppercase) 

def get_char(ch,shift): 
    #get a tally of the each letter 
    common_letter=#letter with most "tallies" 
    return common_letter 
    print(common_letter) 

#finding the shift 
def get_shift(s,ignore): 
    for x in Input: 
     shift=get_char-x 
     if shift=='e': 
      return x 
      print(x) 

def output_plaintext(s,shift): 

#convert back to English based off shift 
    pass 

def main(): 
# main body where i call together my other functions 
    pass 

input("is this decrypted?") 
#if no is inputted re run program with second most common letter 

如何获得每个字母的计数的字符串?

-Nathan

+0

看来你错过了一些缩进这里,格式化,因为它是不应该运行在所有(尤其是最后两个功能)。 – fpietka

+0

缩进在python中是正确的,在复制和粘贴时肯定已经搞乱了。 – Nathannn

回答

1

您可以使用下面的代码获得字符串中的最后一个字符:

string[len(string)-1]

+2

更简单:'string [-1]' – fpietka

3

这可能会帮助你: -

from collections import Counter 
input='Nathannn' 
print Counter(input) 

输出: -

Counter({'n': 3, 'a': 2, 'h': 1, 't': 1, 'N': 1}) 

如果你想忽略大小写使用input.lower(),然后应用Counter(input)

1

这里的另一种方法,如果你不能使用导入的模块,例如collections

>>> string = 'aardvark' 
>>> {letter: string.count(letter) for letter in set(string)} 
{'v': 1, 'r': 2, 'd': 1, 'a': 3, 'k': 1} 
相关问题