Python Counting Vowels - python

I have started on a program to count vowels and have seemed to be getting nowhere. I need to count vowels from a string and then display the vowels. I need to do this by storing the number of occurrences in variables. Like this :
a = 0
b = 0
....
then print the lowest.
Current code (its not that much ):
string = str(input("please input a string: "))
edit= ''.join(string)
print(edit)
I have tried a number of methods just by my self and don't seem to get anywhere.

You could use a dictionary comprehension:
>>> example = 'this is an example string'
>>> vowel_counts = {c: example.count(c) for c in 'aeoiu'}
>>> vowel_counts
{'i': 2, 'o': 0, 'e': 5, 'u': 0, 'a': 2}
Then finding the minimum, maximum etc. is trivial.

>>> a="hello how are you"
>>> vowel_count = dict.fromkeys('aeiou',0)
>>> vowel_count
{'a': 0, 'i': 0, 'e': 0, 'u': 0, 'o': 0}
>>> for x in 'aeiou':
... vowel_count[x]=a.count(x)
...
>>> vowel_count
{'a': 1, 'i': 0, 'e': 2, 'u': 1, 'o': 3}
now from here you can print low nd max

You can use dictionary for this problem. Iterate over each character and if the character is a vowel, put it in dictionary with count 0 and increment its count by 1, and for every next occurrence keep incrementing the count.
>>> string = str(input("please input a string: "))
please input a string: 'Hello how are you'
>>> dt={} # initialize dictionary
>>> for i in string: # iterate over each character
... if i in ['a','e','i','o','u']: # if vowel
... dt.setdefault(i,0) # at first occurrence set count to 0
... dt[i]+=1 # increment count by 1
...
>>> dt
{'a': 1, 'u': 1, 'e': 2, 'o': 3}

word = input('Enter Your word : ')
vowel = 'aeiou'
vowel_counter = {}
for char in word:
if char in vowel:
vowel_counter[char] = vowel_counter.setdefault(char,0)+1
sorted_result = sorted(vowel_counter.items(), reverse=True,key=lambda x : x[1])
for key,val in sorted_result:
print(key,val)

Related

Ignore Whitespace while counting number of characters in a String

I am trying to write a function which will count the number of characters present in an input string and store as key-value in a dictionary.The code is partially working i.e it is also counting the whitespaces present in between 2 words.How do I avoid counting the whitespaces?
#Store Characters of a string in a Dictionary
def char_dict(string):
char_dic = {}
for i in string:
if i in char_dic:
char_dic[i]+= 1
else:
char_dic[i]= 1
return char_dic
print(char_dict('My name is Rajib'))
You could just continue if the character is a white space:
def char_dict(string):
char_dic = {}
for i in string:
if ' ' == i:
continue
if i in char_dic:
char_dic[i] += 1
else:
char_dic[i]= 1
return char_dic
print(char_dict('My name is Rajib')) # {'j': 1, 'm': 1, 'M': 1, 'i': 2, 'b': 1, 'e': 1, 'a': 2, 'y': 1, 'R': 1, 'n': 1, 's': 1}
A cleaner solution would be:
from collections import defaultdict
def countNonSpaceChars(string):
charDic = defaultdict(lambda: 0)
for char in string:
if char.isspace():
continue
charDic[char] += 1
return dict(charDic)
print(countNonSpaceChars('My name is Rajib')) # {'i': 2, 'a': 2, 'R': 1, 'y': 1, 'M': 1, 'm': 1, 'e': 1, 'n': 1, 'j': 1, 's': 1, 'b': 1}
You can delete space -> string = string.replace (" ","")
def char_dict(string):
char_dic = {}
string=string.replace(" ","")
for i in string:
if i in char_dic:
char_dic[i]+= 1
else:
char_dic[i]= 1
return char_dic
print(char_dict('My name is Rajib'))
To simplify things for you, there's a library called collections that has a Counter function that will produce a dictionary of values and their occurrences in a string. Then, I would simply remove the whitespace key from the dictionary if it is present using the del keyword.
from collections import Counter
def char_dict(string):
text = 'My name is Rajib'
c = Counter(text)
if ' ' in c: del c[' ']
print(char_dict('My name is Rajib'))
This method is very readable and doesn't require too much reinventing.

Counting the number of letter characters in a string

I need to have a user enter a string in which any character is allowed. Once entered I need to count each letter character occurrence in the string. So far I have:
s = input("Enter a string: ")
s = s.upper()
all_freq = {}
for i in s:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
print(all_freq)
This is wrong because it includes numbers, spaces and special characters in the count.
Using a list comprehension to filter and Counter (from collections) to count would make it more compact:
from collections import Counter
s = "Hello World!"
result = Counter(c for c in s.upper() if c.isalpha())
print(result)
# Counter({'L': 3, 'O': 2, 'H': 1, 'E': 1, 'W': 1, 'R': 1, 'D': 1})
If you only want to count characters, you can use the isalpha function to check if a character is alphabetical.
s = input("Enter a string: ")
s = s.upper()
all_freq = {}
for i in s:
if i.isalpha():
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
print(all_freq)
Enter a string: Hello World!
{'H': 1, 'E': 1, 'L': 3, 'O': 2, 'W': 1, 'R': 1, 'D': 1}
Hope this helps!
You can also use regex expression to check for characters
import re
s = input("Enter a string: ")
s = s.upper()
all_freq = {}
for i in s:
if bool(re.match('[A-Z]',i)):
if i in all_freq :
all_freq[i] += 1
else:
all_freq[i] = 1
print(all_freq)
Here's the output:
Enter a string: hello hello 1 $
{'H': 2, 'E': 2, 'L': 4, 'O': 2}
Maybe one simple solution is to use string module like bellow:
import string
s = input("Enter a string: ")
ignore = string.whitespace + string.digits + string.punctuation
s = s.upper()
all_freq = {}
for c in s:
if c not in ignore:
all_freq[c] = all_freq.get(c, 0) + 1
print(all_freq)

Creating a function in Python that counts number of letters in a dictionary [duplicate]

This question already has answers here:
Counting each letter's frequency in a string
(2 answers)
Closed 4 years ago.
How do I create a function that will let me input a word, and it will execute to create a dictionary that counts individual letters in the code. I would want it to display as a dictionary, for example, by inputting 'hello' it will display {'e': 1, 'h': 1, 'l': 2, 'o': 1}
I AM ALSO required to have 2 arguments in the function, one for the string and one for the dictionary. THIS IS DIFFERENT to the "Counting each letter's frequency in a string" question.
For example, I think I would have to start as,
d = {}
def count(text, d ={}):
count = 0
for l in text:
if l in d:
count +=1
else:
d.append(l)
return count
But this is incorrect? Also Would i need to set a default value to text, by writing text ="" in case the user does not actually enter any word?
Furthermore, if there were existing values already in the dictionary, I want it to add to that existing list. How would this be achieved?
Also if there were already existing words in the dictionary, then how would you add onto that list, e.g. dct = {'e': 1, 'h': 1, 'l': 2, 'o': 1} and now i run in terminal >>> count_letters('hello', dct) the result would be {'e': 2, 'h': 2, 'l': 4, 'o': 2}
If you can use Pandas, you can use value_counts():
import pandas as pd
word = "hello"
letters = [letter for letter in word]
pd.Series(letters).value_counts().to_dict()
Output:
{'e': 1, 'h': 1, 'l': 2, 'o': 1}
Otherwise, use dict and list comprehensions:
letter_ct = {letter:0 for letter in word}
for letter in word:
letter_ct[letter] += 1
letter_ct
You can use pythons defaultdict
from collections import defaultdict
def word_counter(word):
word_dict = defaultdict(int)
for letter in word:
word_dict[letter] += 1
return(word_dict)
print(word_counter('hello'))
Output:
defaultdict(<class 'int'>, {'h': 1, 'e': 1, 'l': 2, 'o': 1})
def count_freqs(string, dictionary={}):
for letter in string:
if letter not in dictionary:
dictionary[letter] = 1
else:
dictionary[letter] += 1
return dictionary

How to form a dictionary from a string?

word = 'stacks'
word_dict = {} # to form new dictionary formed from
for letter in word:
word_dict[letter] += 1
print word_dict
I want to create a new dictionary from a string, tracking the count of the letters from word. So what I'm trying to get is:
> word_dict = {'s':2, 't':1, 'a':1, 'c':1, 'k':1}
But I can't figure out how to do this. I get KeyError with my current code
Use the collections.Counter() class instead:
from collections import Counter
word_dict = Counter(word)
The Counter does the exact same thing; count occurrences of each letter in word.
In your specific case you didn't first check if the key already exists or provide a default if it doesn't. You could use dict.get() to do that:
word = 'stacks'
word_dict = {} # to form new dictionary formed from
for letter in word:
word_dict[letter] = word_dict.get(letter, 0) + 1
print word_dict
or use dict.setdefault() separately to explicitly set a default before incrementing:
word = 'stacks'
word_dict = {} # to form new dictionary formed from
for letter in word:
word_dict.setdefault(letter, 0)
word_dict[letter] += 1
print word_dict
or test for the key yourself:
word = 'stacks'
word_dict = {} # to form new dictionary formed from
for letter in word:
if letter not in word_dict:
word_dict[letter] = 0
word_dict[letter] += 1
print word_dict
in decreasing order of efficiency.
Or you could use a collections.defaultdict() object to automatically insert a 0 if there the key doesn't yet exist:
from collections import defaultdict
word_dict = defaultdict(int)
for letter in word:
word_dict[letter] += 1
print word_dict
This is essentially what the Counter class does, but the type adds some other niceties such as listing the most common keys or combining counters.
Demo:
>>> from collections import defaultdict, Counter
>>> word = 'stacks'
>>> word_dict = {} # to form new dictionary formed from
>>> for letter in word:
... word_dict[letter] = word_dict.get(letter, 0) + 1
...
>>> word_dict
{'a': 1, 'c': 1, 's': 2, 't': 1, 'k': 1}
>>> word_dict = defaultdict(int)
>>> for letter in word:
... word_dict[letter] += 1
...
>>> word_dict
defaultdict(<type 'int'>, {'a': 1, 'c': 1, 's': 2, 't': 1, 'k': 1})
>>> Counter(word)
Counter({'s': 2, 'a': 1, 'c': 1, 't': 1, 'k': 1})
Try this
from collections import Counter
>>>Counter(word)
Counter({'s': 2, 'a': 1, 'c': 1, 't': 1, 'k': 1})

Program optimisation and working of dictionary in adding key value pairs

this is my program on counting the number of vowels
'''Program to count number of vowels'''
str=input("Enter a string\n")
a=0
e=0
i=0
o=0
u=0
for x in str:
if x=='a':
a=a+1
continue
if x=='e':
e=e+1
continue
if x=='i':
i=i+1
continue
if x=='o':
o=o+1
continue
if x=='u':
u=u+1
continue
count={}
if a>0:
count['a']=a
if e>0:
count['e']=e
if i>0:
count['i']=i
if o>0:
count['o']=o
if u>0:
count['u']=u
print(count)
How can I improve the initial loop for comparison along with the process of filling the dictionary.
While running the program several times I have obtained the following output:
>>>
Enter a string
abcdefgh
{'e': 1, 'a': 1}
>>> ================================ RESTART ================================
>>>
Enter a string
abcdefghijklmnopqrstuvwxyz
{'u': 1, 'a': 1, 'o': 1, 'e': 1, 'i': 1}
>>> ================================ RESTART ================================
>>>
Enter a string
abcdeabcdeiopiop
{'a': 2, 'o': 2, 'i': 2, 'e': 2}
From this I could not figure out how exactly are the key value pairs being added to the dictionary count against my expectation of:
Case 1:
{'a':1, 'e':1}
Case 2:
{'a':1, 'e':1, 'i':1, 'o':1, 'u':1}
Case 3:
{'a':2, 'e':2, 'i':2, 'o':2}
Any help is appreciated.
>>> import collections
>>> s = "aacbed"
>>> count = collections.Counter(c for c in s if c in "aeiou")
>>> count
Counter({'a': 2, 'e': 1})
Or - if you really need to maintain insertion order:
>>> s = 'debcaa'
>>> count=collections.OrderedDict((c, s.count(c)) for c in s if c in "aeiou")
>>> count
OrderedDict([('e', 1), ('a', 2)])
Finally if you want lexicographic ordering, you can either turn your dict/counter/ OrderedDict into a list of tuples:
>>> sorted(count.items())
[('a', 2), ('e', 1)]
and if you want a lexicographically OrderedDict:
>>> sorted_count = collections.OrderedDict(sorted(count.items()))
>>> sorted_count
OrderedDict([('a', 2), ('e', 1)])
A more Pythonic way to do what you want is:
'''Program to count number of vowels'''
s = input("Enter a string\n")
count = {v: s.count(v) for v in "aeiou" if s.count(v) > 0}
print(count)
You shouldn't use str as a variable name, as that is the name of the built-in string type.
Just put a=0 e=0 i=0 o=0 u=0 inside a dictionary like that:
myDict = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}
for x in string:
myDict[x] += 1
print myDict
If the value is not one of the following then a raise of KeyError will come up.
So you can do something like that:
myDict = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
for x in string:
try:
myDict[x] += 1
except KeyError:
continue
print myDict
Note: I've changed the name str to string
You can also see a very good solution by #Amber here

Categories