2015-05-13 25 views
-6

几天前,我制作了一个允许我从字符串中选择一封信的程序,它会告诉我一个选定字母出现的次数。现在我想使用该代码来创建一个程序,它将所有字母和计算每个字母出现的次数。例如,如果我把“dog”放在我的字符串中,我会希望程序说d出现一次,o出现一次,g出现一次。以下是我目前的代码。字母计数器II

from collections import Counter 
import string 
pickedletter=() 
count = 0 
word =() 


def count_letters(word): 
    global count 
    wordsList = word.split() 
    for words in wordsList: 
     if words == pickedletter: 
      count = count+1 
    return count 

word = input("what do you want to type? ") 
pickedletter = input("what letter do you want to pick? ") 
print (word.count(pickedletter)) 
+2

好吧,太好了。那么你的问题是什么? – CoryKramer

+0

这就像你谷歌搜索和发现所有的作品,现在你只是想让我们解决难题... –

+0

问题是我想知道如何计算每个字母目前出现多少次代码 –

回答

2
from collections import Counter 

def count_letters(word): 
    counts = Counter(word) 
    for char in sorted(counts): 
     print char, "appears", counts[char], "times in", word 
+0

是的,我不明白他为什么输入'Counter'但不使用它。 –

+0

他使用它。第一行功能 – Dzarafata

1

我不知道为什么你这个进口任何物件,尤其是Counter。这是我会用的方法:

def count_letters(s): 
    """Count the number of times each letter appears in the provided 
    specified string. 

    """ 

    results = {} # Results dictionary. 
    for x in s: 
     if x.isalpha(): 
      try: 
       results[x.lower()] += 1 # Case insensitive. 
      except KeyError: 
       results[x.lower()] = 1 
    return results 

if __name__ == '__main__': 
    s = 'The quick brown fox jumps over the lazy dog and the cow jumps over the moon.' 
    results = count_letters(s) 
    print(results)