![]() |
VOOZH | about |
Given a text file, count the total number of words in it. This is a common task in text processing, data analysis and file handling.
Example:
Input: Python is easy and powerful.
Output: 5
Sample Text File: (file.txt)
👁 CaptureBelow are the several different methods to perform this task:
This method reads the entire file content into memory and splits it into words. It is simple and fast for small to moderately large files.
Output:
Total Words: 7
Explanation:
In this method, we count only the non-numeric words in a text file. The file is read, split into individual words, and each word is checked to see if it is numeric.
Input File: (sample_file.txt)
Welcome to GeeksforGeeks.
Hello 5 geeks.
Hello World!
Output:
Total Words: 7
Explanation:
In this method, the file is read line by line, each line is split into words, and the total count is updated. This is memory-efficient for large files.
Output:
Total Words: 7
Explanation:
readlines() loads all lines into a list. Less memory-efficient than line-by-line reading for large files but simpler to implement.
Output:
Total Words: 7
Explanation: count += len(line.split()): Splits the line into words and adds the number of words to the total count.