Python 信件柜位二
几天前,我制作了一个程序,允许我从字符串中选择一个字母,它会告诉我所选字母出现了多少次。现在我想用这个代码来创建一个程序,它接受所有的字母并计算每个字母出现的次数。例如,如果我把“dog”作为字符串输入,我希望程序说d出现一次,o出现一次,g出现一次。下面是我当前的代码Python 信件柜位二,python,Python,几天前,我制作了一个程序,允许我从字符串中选择一个字母,它会告诉我所选字母出现了多少次。现在我想用这个代码来创建一个程序,它接受所有的字母并计算每个字母出现的次数。例如,如果我把“dog”作为字符串输入,我希望程序说d出现一次,o出现一次,g出现一次。下面是我当前的代码 from collections import Counter import string pickedletter= () count = 0 word = () def count_letters(word):
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))
我不知道你为什么要为此导入任何内容,尤其是
计数器。这是我将使用的方法:
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)
好的,很好。那么你的问题是什么?就像你在谷歌上搜索并找到了所有的碎片,现在你只想让我们解决这个难题…问题是我想知道如何计算出现在代码中与问题无关的每个字母出现的次数,但是为什么你们都要声明count
为全局变量,并从函数返回它呢?是的,我不明白为什么他导入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)