How to count the number of occurrences of words in a file using Python?

You can use Python’s string operations and dictionaries to count the number of words in a file. Here is an example code:

def count_words(filename):
    word_count = {}
    with open(filename, 'r') as file:
        for line in file:
            words = line.split()
            for word in words:
                if word in word_count:
                    word_count[word] += 1
                else:
                    word_count[word] = 1

    return word_count

filename = 'example.txt'
word_count = count_words(filename)
print(word_count)

In the code above, we have defined a function called count_words to count the number of words. It first creates an empty dictionary called word_count to store the words and their occurrences. Then, we open the file and read its content line by line. For each line, we use the split function to separate it into words. Then, for each word, we check if it’s already in the word_count dictionary. If it is, we increment its count by 1, if not, we add it to the dictionary and set the count to 1. Finally, we return the word_count dictionary.

You can save the above code to a Python file, replacing the file name with the name of the file you want to analyze, and then run this Python program. It will print out each word and its frequency.

广告
Closing in 10 seconds
bannerAds