python: 计算用户输入单词中的元音或辅音数量

3 投票
9 回答
28105 浏览
提问于 2025-04-17 04:08

我是一名大学新生,正在上Python编程课。目前我正在做一个程序,用来统计用户输入中元音字母或辅音字母的数量,以确定模式。

现在,我已经创建了两个列表,我正在尝试找出如何用Python编程来计算元音和辅音。

这是我目前的进展——请记住,我已经在两头做了工作,而中间部分就是进行计数的地方。

#=======================================#
#Zane Blalock's Vowel/Consonants Counter#
#=======================================#

print("Welcome to the V/C Counter!")

#Make List
vowels = list("aeiouy")
consonants = list("bcdfghjklmnpqrstvexz")

complete = False
while complete == False:
    mode = input("What mode would you like? Vowels or Consonants?: ").lower().strip()
    print("")
    print("You chose the mode: " + str(mode))
    print("")
    if mode == "vowels":
        word = input("Please input a word: ")
        print("your word was: " + str(word))
        print("")



        choice = input("Are you done, Y/N: ").lower().strip()
        if choice == "y":
            complete = True
        else:
            print("Ok, back to the top!")
    elif mode == "consonants":
        word = input("please input a word: ")
        print("your word was: " + str(word))
        print("")


        choice = input("Are you done, Y/N: ").lower().strip()
        if choice == "y":
            complete = True
        else:
            print("Ok, back to the top!")
    else:
        print("Improper Mode, please input a correct one")

print("Thank you for using this program")

9 个回答

1

使用正则表达式也是一种选择:

>>> import re
>>> re.findall('[bcdfghjklmnpqrstvwxyz]','there wont be any wovels in the result') 
['t', 'h', 'r', 'n', 't', 'b', 'n', 'v', 'l', 's', 'n', 't', 'h', 'r', 's', 'l', 't']

如果你计算它的长度,你的问题就解决了。

text = 'some text'

wovels = 'aeiou'
consonants = 'bcdfghjklmnpqrstvwxyz'

from re import findall
wovelCount = len(findall('[%s]' % wovels, text))
consonatCount = len(findall('[%s]' % consonants, text))
3
if mode == "vowels":
    print(len(filter(lambda x: x in vowels, word)))
else:
    print(len(filter(lambda x: x in consonants, word)))
>> vc=lambda :sum(word.count(c) for c in vowels)
>> vc2=lambda : len(filter(lambda x: x in vowels, word))
>> timeit.timeit(vc, number=10000)
0.050475120544433594
>> timeit.timeit(vc2, number=10000)
0.61688399314880371

我对我和eumiro的解决方案进行了计时。结果是他的更好。

14

这段代码的意思是……

首先,它定义了一些变量,这些变量可以用来存储信息。接下来,它可能会进行一些操作,比如计算或者处理数据。最后,代码会输出结果,告诉我们计算的结果是什么。

在编程中,变量就像是一个盒子,我们可以把东西放进去,随时拿出来使用。操作就像是对这些东西进行处理,比如加减乘除。输出则是把结果展示给我们,可能是在屏幕上显示,或者保存到文件里。

总的来说,这段代码就是在做一些简单的计算和数据处理,让我们能更好地理解和使用这些信息。

number_of_consonants = sum(word.count(c) for c in consonants)

number_of_vowels = sum(word.count(c) for c in vowels)

撰写回答