开发者

python: Counting the amount of vowels or consonants in a user input word

开发者 https://www.devze.com 2023-04-12 04:54 出处:网络
I\'m a freshman in college, who\'s taking a python coding class. Currently I\'m working on making a program count the amount of vowels or consonants based on a user\'s input to determine 开发者_StackO

I'm a freshman in college, who's taking a python coding class. Currently I'm working on making a program count the amount of vowels or consonants based on a user's input to determine 开发者_StackOverflowthe mode.

currently, I've made two lists, and I'm trying to find out how to program python to count the vowels/consonants.

This is what I have so far - please keep in mind, I've worked on both ends, and the center is where the counting goes.

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


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

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


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

So I timed my and eumiro's solution. His is better

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


Using regex would be an alternative:

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

If you take its length your problem is solved.

text = 'some text'

wovels = 'aeiou'
consonants = 'bcdfghjklmnpqrstvwxyz'

from re import findall
wovelCount = len(findall('[%s]' % wovels, text))
consonatCount = len(findall('[%s]' % consonants, text))


This is a solution which counts consonants and vowels, while excluding punctuation explicitly.

from string import punctuation

x = 'This is an example sentence.'

table = str.maketrans('', '', punctuation)
x = x.translate(table).lower().replace(' ', '')
vowels = set('aeiou')

consonants = sum(i not in vowels for i in x)
vowels = sum(i in vowels for i in x)

print(consonants)  # 14
print(vowels)      # 9


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


Most other answers seem to count each character separately and then sum up the results, which means the code has to iterate over the input string many times and is somewhat inefficient. More efficient would be to count all occurences of all characters in one go, using a 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


How about list comprehension with regular expressions?

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


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


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)

#partly complete.may be unnacurate

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号