In this tutorial, we will see how to get words count in python where words are reading from a file.

How to get Words Count in Python:

Simple source code to get distinct words count in a file.

File Content:

data.txt
What We Talk About When We Talk About Love

Get Words Count in Python:

Reading data from data.txt file in read-only mode and counting distinct words.

WordsCount.py
def word_count(string):
    counts = dict()
    words = string.split()
    for word in words:
        if word in counts:
            counts[word] += 1
        else :
            counts[word] = 1
    return counts
# Opening data.txt file in read only mode
document_text = open('data','r')
text_string = document_text.read().lower()
print("Distinct Words and their frequency")
print(word_count(text_string))

Output:

Terminal
Distinct Words and their frequency
{'what': 1, 'we': 2, 'talk': 2, 'about': 2, 'when': 1, 'love': 1}

Done!

Happy Learning 🙂