Practice Question 10
In this question, we will learn how to write a function that reads a text file and extracts only the “Long Words”—specifically those that have more than 5 characters.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
This logic follows a simple “Scan and Filter” approach:
-
Read and Split: We open
notes.txtand use.split()to get a clean list of words. -
The Length Check: We iterate through the list using a
forloop. -
The Condition: For every word, we use
len(word)to count its characters. -
The Threshold: If the length is greater than 5 (
> 5), we print it. If it is 5 or less, we simply ignore it and move to the next word.
Let’s Code as per the above logic :
def displayLongWords():
f = open("notes.txt", "r")
data = f.read()
wordlist = data.split()
print("Words with length greater than 5:")
for word in wordlist:
# Check if the character count is more than 5
if len(word) > 5:
print(word)
f.close()
# To call the function:
displayLongWords()
Important Notes for Students
Keep these tips in mind to ensure you get full marks for logic and presentation:
-
The Difference between
>and>=: Read the question carefully! If it says “5 or more,” uselen(word) >= 5. If it says “greater than 5,” uselen(word) > 5. -
Output Formatting: Using
print(word)will list them one below the other. If you want them on a single line, useprint(word, end=" "). -
The
split()Advantage: Usingsplit()is better than reading line by line here because it handles cases where multiple long words are on the same line separated by spaces.
Teacher’s Secret Tip for Exams:
If the examiner asks you to display words shorter than 5 characters, simply change the condition from > 5 to < 5. The rest of the program will remain exactly the same.
If the examiner asks you to count long words instead of displaying them, just add a counter variable and increase it whenever len(word) > 5 is true.
If the examiner asks you to store the long words in a new file, you can collect them in a list and then write them to a file using .join().
This is a “Template Logic.” You can use this exact structure to solve many other questions.
-
Want words starting with ‘S’? Change the condition to
if word[0] == 'S':. -
Want words ending with ‘ing’? Change it to
if word.endswith('ing'):
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!