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

时间:2011-10-12 06:41:24

标签: python

我是大学新生,正在参加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 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:3)

if mode == "vowels":
    print(len(filter(lambda x: x in vowels, word)))
else:
    print(len(filter(lambda x: x in consonants, word)))

所以我把我和eumiro的解决方案计时了。他更好

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

答案 2 :(得分: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 :(得分:1)

这是一个计算辅音和元音的解决方案,同时明确排除标点符号。

{{1}}

答案 4 :(得分:0)

Python 2.6.7 (r267:88850, Jun 27 2011, 13:20:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "asfdrrthdhyjkae"
>>> vowels = "aeiouy"
>>> consonants = "bcdfghjklmnpqrstvexz"
>>> nv = 0
>>> nc = 0
>>> for char in a:
...     if char in vowels:
...         nv += 1
...     elif char in consonants:
...         nc += 1
...         
>>> print nv
4
>>> print nc
11
>>> 

答案 5 :(得分:0)

大多数其他答案似乎分别对每个字符进行计数,然后总结结果,这意味着代码必须多次迭代输入字符串并且效率有些低。更有效的方法是使用collections.Counter计算所有角色的所有出现次数:

import collections

s = "This is an example sentence."

counter = collections.Counter(s)

consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
num_consonants = sum(counter[char] for char in consonants)
# result: 14

vowels = 'aeiouAEIOU'
num_vowels = sum(counter[char] for char in vowels)
# result: 9

答案 6 :(得分:0)

使用正则表达式的列表理解如何?

import re
mystr = 'Counting the amount of vowels or consonants in a user input word'
len(re.findall('[aeiou]', mystr, flags=re.I)) # gives the number of vowels
len(re.findall('[b-d]|[f-h]|[j-n]|[p-t]|[v-z]', mystr, flags=re.I)) #gives the number of consonants

答案 7 :(得分:-1)

def main():
    vowels = 'aeiou'
    consonants = 'bcdfghjklmnpqrstvwxyz'
    txt_input = input('Enter a sentence or a word: ').lower()
    vowel = sum(txt_input.count(i) for i in vowels)
    consonant = sum(txt_input.count(i) for i in consonants)
    print("Number of vowels in the string: ",vowel)
    print("Number of consonants in the string: ",consonant)

main()

答案 8 :(得分:-1)

u=input("your sentence:\n")
punctl=[]
vo=["a","e","i","o","u","A","E","I","O","U"]
punct=[",",":",".","(",")","/","&",";","''","!","?","@"]
vf=[]
of=[]
us=(u.split())
for i in range(0,len(us)):
li=list(us[0])
   for i in range(0,len(li)):
        if ((li[0]) in vo)==True:
            vf.append((li[0]))
             li.remove((li[0]))
        else:
             of.append((li[0]))
             li.remove((li[0]))
         us.remove((us[0]))
no=0
lele=len(of)
for i in range(0,lele-1):
    a=(of[no])
    if (a in punct)==True:
        of.remove(a)
        punctl.append(a)
        no=no+1
    if (a in punct)==False:
        no=no+1
print("Number of vowels:",len(vf))
print("Vowels:",vf)
print("Number of consonants:",len(of))
print("Consonants:",of)
print("Number of punctuations:",len(punctl))
print("Punctuation:",punctl)

#部分完成。可能不准确