Python Lab · Experiment 34
Count words, vowels, spaces and upper and lower case letters in a file
PythonWeek 7JNTUH R22 · CS206ES
Aim
To write a Python function that reads a file file1.txt and displays the number of words, vowels, blank spaces, lower case letters and upper case letters in it.
Algorithm
- Read the file name. Open the file and read all its text. If it does not exist, print an error and stop.
- Count the words as the length of the list returned by
text.split(). - Set the counters for vowels, spaces, lower case and upper case letters to 0.
- Go through the text one character at a time:
- if it is one of
aeiouAEIOU, add 1 to vowels; - if it is a space
" ", add 1 to spaces; - if
isupper()is true, add 1 to upper case; ifislower()is true, add 1 to lower case.
- if it is one of
- Display all five counts.
Program
def file_statistics(file_name):
try:
with open(file_name, "r") as f:
text = f.read()
except FileNotFoundError:
print("Cannot open file", file_name)
return
words = len(text.split())
vowels = spaces = lower = upper = 0
for ch in text:
if ch in "aeiouAEIOU":
vowels += 1
if ch == " ":
spaces += 1
if ch.isupper():
upper += 1
elif ch.islower():
lower += 1
print("Number of words :", words)
print("Number of vowels :", vowels)
print("Number of blank spaces :", spaces)
print("Number of lower case letters:", lower)
print("Number of upper case letters:", upper)
file_name = input("Enter file name: ")
file_statistics(file_name)Output
Python is Easy to Learn.
I Love Coding in PythonEnter file name: file1.txt
Number of words : 10
Number of vowels : 14
Number of blank spaces : 8
Number of lower case letters: 31
Number of upper case letters: 7Recorded by running this exact program. Typed input appears after each prompt.
How it works
Blank spaces here means the space character " " only. Newlines and tabs are not counted as blank spaces. Words are counted with split(), which splits at any whitespace.
Checking the output by hand for file1.txt:
- Words: 5 on each line, so 10.
- Blank spaces: 4 on each line, so 8.
- Vowels: line 1 has o, i, E, a, o, e, a (7) and line 2 has I, o, e, o, i, i, o (7), so 14. The letter y is not counted as a vowel.
- Upper case: P, E, L on line 1 and I, L, C, P on line 2, so 7.
- Letters: 19 on each line, 38 in total, so lower case = 38 − 7 = 31. The full stop and the newlines are neither upper nor lower case.
isupper() and islower() are true only for letters, so digits and punctuation are not counted in either.
Common mistakes
Counting only lower case vowels with
"aeiou". Capital vowels such asEandIare then missed. Check"aeiouAEIOU"or usech.lower() in "aeiou".Counting words by counting spaces and adding 1. This is wrong when there are several lines, double spaces or spaces at the end;
len(text.split())is correct.Treating every character that is not upper case as lower case. Spaces, digits, punctuation and newlines are neither; use
islower()for lower case.Using
if/eliffor the vowel check and the case check together. A vowel is also a letter, so all checks must be able to count the same character; use separateifstatements for separate counts.
Viva questions
Try to answer each one aloud before you open it.
What do isupper() and islower() return for a digit or a space?
Both return
False, because these characters have no case. Only letters can be upper or lower case.How does len(text.split()) count words?
split()with no argument breaks the text at every run of spaces, tabs and newlines and returns a list of the words.lengives the number of items in that list.Why is the file read with read() and not readline() here?
read()returns the whole file as one string, so one loop can go through every character.readline()would return only one line at a time.What other string methods test the type of a character?
isalpha()for letters,isdigit()for digits,isspace()for whitespace andisalnum()for letters or digits.Why does the function return early when the file is missing?
If the file cannot be opened there is no text to count. The function prints an error and returns, instead of crashing with a traceback.
Learn the concepts
- Python File Handling: Read, Write and Append Files (with open and pathlib)
- Python Strings: Indexing, Slicing, Methods and f-strings
- Python Functions: def, Parameters and return Explained Simply
- Python if else: Choose Between Two Paths
- Python for Loops in Depth: range, enumerate, zip, Dictionaries and for-else