Python File I/O: Takes a text file as input and returns the number of words of a given text file
Python File I/O: Exercise-18 with Solution
Write a Python program that takes a text file as input and returns the number of words of a given text file.
Note: Some words can be separated by a comma with no space.
words.txt: Write a Python program that accept some words and count the number of distinct words. Print the number of distinct words and number of occurrences for each distinct word according to their appearance.
Sample Solution:
Python Code:
def count_words(filepath):
with open(filepath) as f:
data = f.read()
data.replace(",", " ")
return len(data.split(" "))
print(count_words("words.txt"))
Sample Output:
33
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to remove newline characters from a file.
Next: Write a Python program to extract characters from various text files and puts them into a list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/file/python-io-exercise-18.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics