Search code examples
pythonhistogram

vowels histogram in a text in python


I need a program that receives a text (only letters and space) and depending on the number of vowels will show us "*" for each (a,e,i,o,u) in the text and at the end will count the ("the")s with any spelling (lower or upper case). My program works well but the output will only show me the number of vowels more than 0. But I want to see 0 if one is not in the text. (without using a function)

import string
lowercase_letters = list(string.ascii_lowercase)
uppercase_letters = list(string.ascii_uppercase)
letters = lowercase_letters + uppercase_letters
string = input()
stri = string.lower()
if not(string.replace(' ', '').isalpha()):
    exit()
else:
    words = stri.split()
    counted_the = stri.count("the")
    chars = [char for char in stri if char != " " and char in letters]
    vowels = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
    for key, value in vowels.items():
        counted = chars.count(key)
        vowels[key] = counted
        if counted > 0:
            print(key, "*" * counted)
    if counted_the == 0:
        print("zero")
    else:
        print(counted_the)

Solution

  • If you want to print a blank string (i.e. no *) for every vowel that are not present in the string, you can just remove the if check for counted from your code like below -

    vowels = ["a", "e", "i", "o", "u"] # No need for a dictionary
    for vowel in vowels:
        counted = chars.count(vowel)
        print(vowel, "*" * counted) # Here for counted value 0 no * will be printed
    

    Input

    hello
    

    Output

    a
    e *
    i
    o *
    u
    zero
    

    Assuming you want to print that no vowel present only once instead of individual vowel count, you can use all() like this -

    for vowel in vowels.keys(): # vowels.keys() will return only the vowel chars as we don't need the value here
        counted = chars.count(vowel)
        vowels[vowel] = counted
        if counted > 0:
            print(vowel, "*" * counted)
    
    if all(not i for i in vowels.values()): # Check if all the values in dictionary vowels are zero
        print("No vowel present in", string)
    

    Input

    fghj
    

    Output

    No vowel present in fghj
    zero
    

    Also you might want to check if the variables you have declared are really needed or not. For example, vowels need not be a dictionary as you are not using it store (and later use) any values. Also try to rename the variable string to something else