几天前,我制作了一个程序,允许我从字符串中选择一个字母,它会告诉我所选字母出现的次数。现在我想使用该代码创建一个程序,该程序接收所有字母并计算每个字母出现的次数。例如,如果我把“dog”作为我的字符串,我希望程序说d出现一次,o出现一次,g出现一次。这是我目前的代码。
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))
答案 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
答案 1 :(得分: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)