π Day 88/150 – Count Words in a File in Python
Counting the number of words in a file is a common task in Python. It's useful for text analysis, document processing, data cleaning, and many real-world applications. Python provides several simple ways to count words efficiently.
In this post, we'll explore four different methods to count the words in a file.
Method 1 – Using read() and split()
Total words: 8
Read the entire file and split the text into words.with open("sample.txt", "r") as file: content = file.read() words = content.split() print("Total words:", len(words))
Output
Explanation:
- read() reads the complete file.
- split() separates the text into words using whitespace.
- len() returns the total number of words.
Method 2 – Using a for Loop
Read the file line by line and count the words in each line.
Total words: 8Outputcount = 0 with open("sample.txt", "r") as file: for line in file: count += len(line.split()) print("Total words:", count)
Explanation:
- Read one line at a time.
- Split each line into words.
- Add the number of words to the counter.
Method 3 – Using sum()
A concise and efficient approach.
with open("sample.txt", "r") as file: count = sum(len(line.split()) for line in file) print("Total words:", count)
Output
Total words: 8
Explanation:
- line.split() returns the words in each line.
- len() counts the words.
- sum() adds the counts from all lines.
Method 4 – Taking File Name from User
Allow the user to specify the file to analyze.
filename = input("Enter file name: ") with open(filename, "r") as file: content = file.read() print("Total words:", len(content.split()))
Sample Input
Total words: 8sample.txt
Output
Explanation:
- Accepts a file name from the user.
- Reads the file.
- Counts the total number of words.
Comparison of Methods
| Method | Best For |
|---|---|
| read() + split() | Small text files |
| for Loop | Understanding the counting logic |
| sum() | Clean and memory-efficient |
| User Input | Interactive applications |
π₯ Key Takeaways
- split() is the easiest way to separate text into words.
- read() works well for small files.
- Reading the file line by line is more memory-efficient for larger files.
- sum() with a generator expression provides a concise solution.
- Word counting is widely used in text processing, document analysis, and NLP applications.


0 Comments:
Post a Comment