如何制作一个计算字母并产生输出语句的程序?

How to make a program that counts letters and produces output statements?

对于这个程序,我真的不知道从这里该何去何从。这是我尝试做的:

# Purpose: This function takes an alphabetic string and prints out the number
# of times each letter(upper-or lower-case) is in the string
# Parameter: string - a string of only alphabetic characters
# Return: None

def letter_counter(string):
    counter = 0
    string = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    letter = [ ] # ?

    while counter <= len(string):
        for letter in string: 
            if i == string[counter]:
                counter += 1 
                return counter

    print("The letter", letter, "is in", string, count, "time(s)")
    # Do I use append here? For loops? etc.?

输出应该如下所示:

count("bAseBalls")
Letter b is in bAseBalls 2 time(s)
Letter a is in bAseBalls 2 time(s) 
Letter s is in bAseBalls 2 time(s)
Letter e is in bAseBalls 1 time(s)
Letter l is in bAseBalls 2 time(s) 

我是否只是使用大量 'if' 语句来打印出每个字母在字符串中出现的次数?您会推荐此程序中的 'while' 与 'for' 循环吗?任何帮助将不胜感激。提前致谢!

你想多了。您需要做的就是将字符串拆分为小写字母,然后使用 collections.Counter 计算每个字母在列表中出现的次数。

#Imports counter to count items.
from collections import Counter

#Defines letter counter which takes string as an argument.
def letter_count(string):
    #Creates a copy of the string in lower case.
    lower_string = string.lower()
    #Uses list to make a list of letters in the string, and then uses counter to count how many letters are in the list.
    letters = Counter(list(lower_string))
    #Loops through the list of (element, count pairs).
    for letter in letters.items():
        #Prints the string with the element and the count.
        print("Letter", letter[0], "is in", string, letter[1], "time(s)")

letter_count("BaseBalLs")

您不必重新发明轮子来计算字符串中的字符数。 python 可以像对待列表一样遍历字符串。更好的是:python 有自己的 ascii 字母:string.ascii_lowercase

dict comprehensions 在这里也可以帮助您保持代码简单,pythonic:

import string

def count_letters(word):
    l_word = word.lower()
    counts = { c: l_word.count(c) for c in string.ascii_lowercase if l_word.count(c) > 0 }
    for char, count in counts.items():
        print("The letter {} is in {} {} time(s)".format(char, word, count))


count_letters('bAseBall')

输出:

The letter a is in bAseBall 2 time(s)
The letter s is in bAseBall 1 time(s)
The letter b is in bAseBall 2 time(s)
The letter e is in bAseBall 1 time(s)
The letter l is in bAseBall 2 time(s)