KnowledgeBoat Logo

Computer Science

Write a function AMCount() in Python, which should read each character of a text file STORY.TXT, should count and display the occurrence of alphabets A and M (including small cases a and m too).

Example :
If the file content is as follows :
Updated information
As simplified by official websites.

The EUCount() function should display the output as :
A or a : 4
M or m : 2

Python File Handling

3 Likes

Answer

Let the file "STORY.TXT" include the following sample text:

Updated information
As simplified by official websites.
def AMCount(file_path):
    count_a = 0
    count_m = 0
    with open(file_path, 'r') as file:
        ch = ' '
        while ch:
            ch = file.read(1)
            ch_low = ch.lower()
            if ch_low == 'a':
                count_a += 1
            elif ch_low == 'm':
                count_m += 1

    print("A or a:", count_a)
    print("M or m:", count_m)

AMCount("STORY.TXT")
Output
A or a: 4 
M or m: 2

Answered By

2 Likes


Related Questions