2017-02-18 99 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} 
相關問題