How to Create a Word Frequency Counter from a Text File

90 views

How to Create a Word Frequency Counter from a Text File

How to Create a Word Frequency Counter from a Text File

I need to count the frequency of each word in a text file. How can I do this in Python?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

You can read the file, split the words, and use a dictionary to count occurrences.

Code Example:

def word_frequency(file_name):
    freq = {}
    with open(file_name, 'r') as file:
        for word in file.read().lower().split():
            freq[word] = freq.get(word, 0) + 1
    return freq

print(word_frequency("example.txt"))

This function returns a dictionary where keys are words and values are their frequencies in the specified file.

solveurit24@gmail.com Changed status to publish February 16, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.