Practice Question 13
In this question, we will learn how to write a function that reads a file and displays the word count for every single line. This is a great way to analyze the structure and density of a document.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To solve this, we need to treat the file as a list of sentences and then break each sentence into words. Here is the teacher’s breakdown:
-
Read Line by Line: We use
f.readlines()to get a list where every item is one line from the file. -
The Outer Loop: We go through each line one by one using a
forloop. -
The Split Strategy: Inside the loop, we use
line.split(). This breaks the current line into a list calledwordlist. -
The Count: We use
len(wordlist)to find out how many words are in that specific line. -
The Display: We use a counter
line_noto show which line we are currently describing.
Let’s Code as per the above logic :
def lineWiseWordCount():
f = open("records.txt", "r")
linelist = f.readlines()
line_no = 1
for line in linelist:
wordlist = line.split()
count = len(wordlist)
print("Line ", line_no, ":", count, "words")
line_no += 1
f.close()
# To call the function:
lineWiseWordCount()
Important Notes for Students
Pay attention to these small details to ensure your logic is “Board Exam” ready:
-
Handling Empty Lines: If a line is empty (just a newline),
line.split()will return an empty list[]. Thelen()function will return0, so your output will correctly say “0 words.” -
The
line_noCounter: Notice that we initializeline_no = 1outside the loop and increment it inside the loop. This ensures we don’t start counting lines from zero, which is more user-friendly. -
Why
readlines()? This method is ideal when you need to know exactly where one line ends and another begins.
Teacher’s Secret Tip for Exams:
If the question asks you to only count lines that have more than 10 words, simply wrap the print statement in an if condition: if count > 10: print(...). The rest of your logic stays exactly the same!
Want to practice more? If you found this helpful, I have compiled a full list of 30 practice problems just like this one. Each question focuses on a different logic to help you become a pro at File Handling.
Click here to view the full 30-Question Practice Set
Exam Special Recommendation: If you are studying in 12th class and preparing for your board exam, then go for the “Computer Science with Python Sample Paper Book“. It contains 3 previous years’ papers and 7 practice papers solved strictly as per the CBSE pattern. Click here to purchase your copy!