简体   繁体   中英

Python string vowel counter

I'm trying to create a program that counts the number of vowels in a given sentance and returns the most common occuring vowel(s) and the number of time it(they) occur and the same for the least common vowel(s) whilst ignoring those that do not occur at all. Here is my current code

import collections, string

print("""This program will take a sentence input by the user and work out
the least common vowel in the sentence, vowels being A, E, I, O and U.
""")

sent = None

while sent == None or "":
    try:
        sent = input("Please enter a sentence: ").lower()
    except ValueError:
        print("That wasn't a valid string, please try again")
        continue

punct = str(set(string.punctuation))
words = sent.split()
words = [''.join(c for c in s if c not in string.punctuation) for s in words]

a = 0
e = 0
i = 0
o = 0
u = 0

for c in sent:
    if c is "a":
        a = a + 1
    if c is "e":
        e = e + 1
    if c is "i":
        i = i + 1
    if c is "o":
        o = o + 1
    if c is "u":
        u = u + 1

aeiou = {"a":a, "e":e, "i":i, "o":o, "u":u}
print("The most common occuring vowel(s) was: ", max(aeiou, key=aeiou.get))
print("The least common occuring vowel(s) was: ", min(aeiou, key=aeiou.get))

ender = input("Please press enter to end")

Currently, it prints out the most and least occuring vowel, not all, and it does not print out the number of occurences either, nor does it ignore those that do not occur at all. Any help as to how I would go about doing this would be appreciated.

Mant Thanks

A collections.Counter would be great here!

vowels = set('aeiou') 
counter = collections.Counter(v for v in sentence.lower() if v in vowels)
ranking = counter.most_common()
print ranking[0]  # most common
print ranking[-1]  # least common

A few notes on your code.

  • don't use a = a + 1 , use a += 1 .
  • don't use is to compare strings, use == : if c == a: a += 1 .

Finally, to get the max, you need the entire item, not just the value. This means (unfortunately) that you'll need a more involved "key" function than just aeiou.get .

# This list comprehension filters out the non-seen vowels.
items = [item for item in aeiou.items() if item[1] > 0]

# Note that items looks something like this:  [('a', 3), ('b', 2), ...]
# so an item that gets passed to the key function looks like
# ('a', 3) or ('b', 2)
most_common = max(items, key=lambda item: item[1])
least_common = min(items, key=lambda item: item[1])

lambda can be tricky the first few times that you see it. Just note that:

function = lambda x: expression_here

is the same as:

def function(x):
    return expression_here

you can use dictionary:

>>> a = "hello how are you"
>>> vowel_count = { x:a.count(x) for x in 'aeiou' }
>>> vowel_count 
{'a': 1, 'i': 0, 'e': 2, 'u': 1, 'o': 3}
>>> keys = sorted(vowel_count,key=vowel_count.get)
>>> print "max -> " + keys[-1] + ": " + str(vowel_count[keys[-1]])
max -> o: 3
>>> print "min -> " + keys[0] + ": " + str(vowel_count[keys[0]])
min -> i: 0

count counts the number of occurrence of element

you can also do it using list comprehension :

>>> vowel_count = [ [x,a.count(x)] for x in 'aeiou' ]
>>> vowel_count
[['a', 1], ['e', 2], ['i', 0], ['o', 3], ['u', 1]]
>>> sorted(vowel_count,key=lambda x:x[1])
[['i', 0], ['a', 1], ['u', 1], ['e', 2], ['o', 3]]
class VowelCounter:
    def __init__(self, wrd):
        self.word = wrd
        self.found = 0
        self.vowels = "aeiouAEIOU"
    def getNumberVowels(self):
        for i in range(0, len(self.word)):
            if self.word[i] in self.vowels:
                self.found += 1
        return self.found

    def __str__(self):
        return "There are " + str(self.getNumberVowels()) + " vowels in the String you entered."
def Vowelcounter():
    print("Welcome to Vowel Counter.")
    print("In this program you can count how many vowel there are in a String.")
    string = input("What is your String: \n")
    obj = VowelCounter(string)
    vowels = obj.getNumberVowels()
    if vowels > 1:
        print("There are " + str(vowels) + " vowels in the string you entered.")
    if vowels == 0:
        print("There are no vowels in the string you entered.")
    if vowels == 1:
        print("There is only 1 vowel in the string you entered.")
    recalc = input("Would you like to count how many vowels there are in a different string? \n")
    if recalc == "Yes" or recalc == "yes" or recalc == "YES" or recalc == "y" or recalc == "Y":
        Vowelcounter()
    else:
        print("Thank you")
Vowelcounter()

From my point of view, just for simplicity, I would recommend you to do it in the following way:

 def vowel_detector():
        vowels_n = 0
        index= 0
        text = str(input("Please enter any sentence: "))
        stop = len(text)
        while index != stop:
            for char in text:
                if char == "a" or char == "e" or char == "i" or char=="o" or char == "u":
                    vowels_n += 1
                    index += 1
                else: 
                    index +=1




          print("The number of vowels in your sentence is " + str(vowels_n))
        return

    vowel_detector()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM