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:

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.
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 =
print("Distinct Words and their frequency")


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


Happy Learning 🙂