w3resource

Python File I/O: Count the frequency of words in a file

Python File I/O: Exercise-10 with Solution

Write a Python program to count the frequency of words in a file.

Contain of text.txt

What is Python language?                                                
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in 
languages such as C++ or Java.                                         
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles.It features a dynamic type system and automatic memory management and has a large and comprehensive standard library. The best way we learn anything is by practice and exercise questions. We  have started this section for those (beginner to intermediate) who are familiar with Python.

Sample Solution:-

Python Code:

from collections import Counter
def word_count(fname):
        with open(fname) as f:
                return Counter(f.read().split())

print("Number of words in the file :",word_count("test.txt"))

Sample Output:

Number of words in the file : Counter({'this': 7, 'Append': 5, 'text.': 5, 'text.Append': 2, 'Welcome': 1, 'to
': 1, 'w3resource.com.': 1})  

Flowchart:

Flowchart: File I/O: Count the frequency of words in a file.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to count the number of lines in a text file.
Next: Write a Python program to get the file size of a plain file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-10.php