chevron_left
480 points
9 4 2

Some people are studying how the `syllables` of a language are formed as without `vowels` it would be very difficult to pronounce a word. One might want to know the frequency of vowels in a word or in a string. In this article we will create a program that will calculate the `number of vowels` a string. In English the vowels are `a, e, i, o and u`. We will use 4 different methods such as `for loop`, `while loop`, the built-in `count`, and `list comprehension` to build the programs. We will also convert the python script to windows executable.

list

Photo by Pexels

1.  What is the problem #

The problem is about creating a program that can count the number of vowels in a given string. The vowels that we are going to count are a, e, i, o, u. For example given a string of This image is beautiful. There are 2 a, 2 e, 4 i, 0 o and 1 u. The total is 9.

2.  User input types #

a) Prompt the user to input string.

code

input_string = input('input a string? ')

b) Let the user name a file with a fixed filename like mytext.txt.

mytext.txt

It is not about the wealth but health.
Man does not learn from history he became history.

We will read the text file and save all lines to a list. Then parse each line in the list and find the vowels.

code

fn = 'mytext.txt'
textvar = []  # save all lines to a list
with open(fn, 'r') as f:
    for lines in f:
        line = lines.rstrip()
        textvar.append(line)

for line in textvar:
    print(line)

output

It is not about the wealth but health.
Man does not learn from history he became history.

We can then examine the vowels per line read.

3.  How to solve the problem #

We will present 4 methods to solve the problem, namely using for loop, while loop, count, and list comprehension.

3.1.  Solution 1: Using for loop

loop_method.py
code

vowels = ['a', 'e', 'i', 'o', 'u']    
def count_vowels_loop_method(mystr):
    """Count vowels using for loop.
    """
    cnt = 0
    for c in mystr:
        if c in vowels:
            cnt += 1
    return cnt

if __name__ == '__main__':
    # Prompt the user of the string.
    input_string = input('input a string? ')
    input_string = input_string.lower()  # convert all to lower case

    cnt = count_vowels_loop_method(input_string)
    print(f'num_vowels: {cnt}')

command line

PS F:\vowels> python loop_method.py

output

input a string? this place is beautiful
num_vowels: 9

3.2.  Solution 2: Using while loop

while_method.py
code

vowels = ['a', 'e', 'i', 'o', 'u']    
def count_vowels_while_method(mystr):
    mystr_size = len(mystr)  # number of characters
    cnt = 0  # vowel counter

    index = 0
    while index < mystr_size:  # stop looping when index equals mystr_size
        c = mystr[index]  # get the char at index index
        if c in vowels:
            cnt += 1
        index += 1  # increment the index for while termination
    return cnt

if __name__ == '__main__':
    input_string = input('input a string? ')  # Prompt the user of the string.
    input_string = input_string.lower()  # convert all to lower case

    cnt = count_vowels_while_method(input_string)
    print(f'num_vowels: {cnt}')

output

input a string? Faced with what is right, to leave it undone shows a lack of courage.
num_vowels: 22

3.3.  Solution 3: Using built-in count

The count is a list method that returns the number of times the parameter value appears in the list. In this method we will use the input string from a file.

mytext.txt

It is not about the wealth but health.
Man does not learn from history he became history.

count_method.py

code

def count_vowels_count_method(mystr):
    mystr = mystr.lower()  # convert to lower case
    cnt_a = mystr.count('a')
    cnt_e = mystr.count('e')
    cnt_i = mystr.count('i')
    cnt_o = mystr.count('o')
    cnt_u = mystr.count('u')
    return cnt_a + cnt_e + cnt_i + cnt_o + cnt_u

if __name__ == '__main__':
    # Read the string from file.
    fn = 'mytext.txt'
    text_list = []  # list variable to hold the lines
    with open(fn, 'r') as f:
        for line in f:
            text_list.append(line.rstrip())  # save line, remove the newline with rstrip()

    # Read each line in the list and count the vowels.
    total_vowels = 0
    for s in text_list:
        total_vowels += count_vowels_count_method(s)

    print('text content:')
    for s in text_list:
        print(s.lower())
    print(f'num_vowels: {total_vowels}')

output

text content:
it is not about the wealth but health.
man does not learn from history he became history.
num_vowels: 27

3.4.  Solution 4: Using list comprehension

A list comprehension is a method that can be used to create a new list built from conditions. We will use string input from a file.

mytext.txt

It is not about the wealth but health.
Man does not learn from history he became history.

list_comprehension_method.py

code

vowels = ['a', 'e', 'i', 'o', 'u']
def count_vowels_list_comprehension(mystr):
    mystr = mystr.lower()  # convert to lower case
    vowel_list = [1 for c in mystr if c in vowels]
    num_vowels = sum(vowel_list)
    return num_vowels

if __name__ == '__main__':
    # Read the string from file.
    fn = 'mytext.txt'
    text_list = []  # list variable to hold the lines
    with open(fn, 'r') as f:
        for line in f:
            text_list.append(line.rstrip())  # save the line read

    # Read each line in the list and count the vowels.
    total_vowels = 0
    for s in text_list:
        total_vowels += count_vowels_list_comprehension(s)

    print('text content:')
    for s in text_list:
        print(s.lower())
    print(f'num_vowels: {total_vowels}')

output

text content:
it is not about the wealth but health.
man does not learn from history he became history.
num_vowels: 27

4.  Python script to windows exe #

We can convert a python script to a windows executable with the use of the python package pyinstaller.

Install the package with the following command.

pip install --upgrade pyinstaller

Let's compile loop_method.py.

pyinstaller loop_method.py -F

The option -F means to create a one-file bundled executable. The compiled exe file will be located in the dist folder on the folder where loop_method.py is located.

5.  Conclusion

We created a program or script to count the number of vowels in the string. There is for and while loop, built-in count and list comprehension methods. Users can enter the input from the prompt and from the file. There is also one example shown on how to convert a python script to a windows executable with the use of pyinstaller package.

6.  References

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Order a list of numbers without built-in sort, min, max functions in Python Ferdy - Aug 4
Sum of odd numbers from 1 to 50 in Python Ferdy - Aug 10
Sum of even numbers from 1 to 100 in Python Ferdy - Aug 8
Add to the list in a loop using python amr12345a - Jun 2
Python program to check user id contains only letters, numbers and underscores Ferdy - Aug 17
Format a number of seconds to date using python amr12345a - Jun 6
Write a 'C' program to find the day of the given date. Bushra Rubab - Sep 9
How to Reverse a given string in python Ankur Ranpariya - Jul 21
How to exit a C++ program? Bushra Rubab - Sep 5
Write a Program to Print First x Terms of the Series 3n+2 which are not Multiples of 4 beekip - Sep 20
How to check if a key exists in a Python dictionary Ferdy - Aug 30
Which method is used to delete a directory in Python Ferdy - Aug 24
How to Read a File line by line in Python umasivasu21 - Aug 2
Given a List of Non Negative Integers, Arrange them such that they Form the Largest Number Ankur Ranpariya - Jul 27
Check if a number is between two values using python amr12345a - Jun 1
Python program to print even numbers from the list Ankur Ranpariya - Jul 16
Which Operator can be used for String Manipulation in Python Ankur Ranpariya - Jul 22
Python replace last character in string amr12345a - May 31
Python convert scientific notation string to float Aizhamal Zhetigenova - Jun 1
Given a string, return a string where for every char in the original, there are two chars. Ankur Ranpariya - Jul 19