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

2024-05-14 22:06:30 发布

您现在位置:Python中文网/ 问答频道 /正文

关于这个项目我真的不知道该怎么办。以下是我试图做的:

# 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循环吗?任何帮助都将不胜感激。提前谢谢!你知道吗


Tags: oftheinforstringiftimeis
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")

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

在这里,dict理解还可以帮助您保持代码的简单性和python性:

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)

相关问题 更多 >

    热门问题