ByteBoard Notes Notes

Count the words "the" and "this" in a text file and display the lines that begin with T

Computer Science XII · Experiment 09 of 29 · Python

12-CSPython programs
Expt. No.09
Page No.18

Count words and lines starting with T

Aim

To write a Python program with two functions: one counts the words "the" and "this" in a text file (in any case), the other displays the lines that start with the letter T.

Concepts used

Algorithm

  1. count_words(): read the file, split it into words, and count words equal to "the" or "this" after converting each to lowercase.
  2. lines_with_t(): read the lines and display those whose first character is "T".
  3. Call both functions.

Program

# Count "the" and "this", and show lines beginning with T def count_words(filename):    with open(filename, "r") as f:        words = f.read().split()    the_count = 0    this_count = 0    for w in words:        if w.lower() == "the":            the_count += 1        elif w.lower() == "this":            this_count += 1    print("Number of 'the' :", the_count)    print("Number of 'this':", this_count) def lines_with_t(filename):    with open(filename, "r") as f:        lines = f.readlines()    print("Lines starting with T:")    for line in lines:        if line[0] == "T":            print(line.rstrip()) count_words("notes.txt")lines_with_t("notes.txt")

A marked line continues the line above it. In your file, write it on the same line.

Input file

notes.txt4 lines
The sun rises in the east.
This is the first line of the story.
Tara likes this book.
We read the book in the library.

Output

$ python count_the_this_lines_t.py
Number of 'the' : 6 Number of 'this': 2 Lines starting with T: The sun rises in the east. This is the first line of the story. Tara likes this book.

✓ Printed by running this program, not typed by hand.

Result

"the" was counted 6 times (twice in each of lines 1, 2 and 4, including "The" at the start of line 1) and "this" 2 times. Three lines begin with T: the ones starting "The", "This" and "Tara".

Viva voce: what the examiner may ask

01Why is lower() used before comparing?

So that "The", "THE" and "the" are all counted as the same word.

02What does rstrip() remove?

Spaces and the \n at the right end of the string, so no blank line is printed after each line.

03Would "the." with a full stop be counted?

No. split() keeps punctuation, so "the." is not equal to "the".

Variations for the lab test

  1. Count the lines that do not start with T.
  2. Count words that end with "e".
  3. Display the longest line in the file.
! Common mistake Using "the" in line counts "the" inside other words such as "there" and "other".
Back to the 12-CS index