4777

Python string vowel counter

Question:

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

Answer1:

A <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">collections.Counter</a> 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 <hr />

A few notes on your code.

<ul><li>don't use a = a + 1, use a += 1.</li> <li>don't use is to compare strings, use ==: if c == a: a += 1.</li> </ul>

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]) <hr />

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

Answer2:

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

Answer3:

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

Recommend

  • Python - AttributeError: 'list' object has no attribute
  • Strip Punctuation From String in Python
  • Counting word occurrences in csv and determine row appearances
  • Regex to remove single characters from string
  • Sort ignoring punctuation (Java)
  • Search a text with single quote
  • URL replace with anchor, not replacing existing anchors
  • C++: How do null characters work in std::string?
  • Remove standard english language stop words in Stanford Topic Modeling Toolbox
  • PHP: regular expression to remove `â` or `â€`?
  • Сounting vowels in javascript
  • C duplicate character,character by character
  • Split string into chunks (of different size) without breaking words
  • Using string.matches to check if last character is vowel
  • How do I remove the last vowel in a string in Ruby?
  • help('modules') crashing? Not sure how to fix
  • Python: Split a String Field into 3 Separate Fields using Lambda
  • Can XOR be expressed using SKI combinators?
  • how can I compare dates in array to find the earliest one?
  • Divide a $1 by 3 and adjusting 1 cent
  • how to get username into sql trigger when multiple users signed on from asp membership
  • How do I shift the decimal place in Python?
  • RxJava debounce by arbitrary value
  • std::remove_copy_if_ valgrind bytes in block are possibly lost in loss record
  • D3 get axis values on zoom event
  • C: Incompatible pointer type initializing
  • Django: Count of Group Elements
  • Why value captured by reference in lambda is broken? [duplicate]
  • How to check if every primary key value is being referenced as foreign key in another table
  • How to handle AllServersUnavailable Exception
  • Release, debug version and Authorization Google?
  • How to get next/previous record number?
  • Is there a mandatory requirement to switch app.yaml?
  • PHP: When would you need the self:: keyword?
  • Why joiner is not used after Sequence generator or Update statergy
  • apache spark aggregate function using min value
  • Does armcc optimizes non-volatile variables with -O0?
  • Recursive/Hierarchical Query Using Postgres
  • Sorting a 2D array using the second column C++
  • UserPrincipal.Current returns apppool on IIS