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

时间:2018-01-15 16:04:16

标签: python python-3.x python-3.5

我真的不知道从这里开始关于这个项目的去处。以下是我试图制作的内容:

# 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) 

我是否只是使用了很多&#39; if&#39;打印出每个字母出现在字符串中的次数的语句?你会推荐&#39; while&#39; vs&#39; for&#39;在这个程序中循环?任何帮助将不胜感激。提前谢谢!

2 个答案:

答案 0 :(得分:2)

你正在思考它。您需要做的就是将字符串拆分为小写字母,然后使用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")

答案 1 :(得分:1)

您不必重新发明轮子来计算字符串中的字符数。 python可以迭代一个字符串就像它是一个列表一样。甚至更好:python有自己的ascii字母:from wand.image import Image as WImage img = WImage(filename='hat.pdf', resolution=100) # bigger img

dict comprehensions也可以帮助你保持你的代码简单和pythonic:

string.ascii_lowercase

输出:

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')