How to Count Words in File To count the number of words in a text file using Python
Published on Aug. 22, 2023, 12:16 p.m.
To count the number of words in a text file using Python, you can open the file, read its contents, split the contents into individual words, and then count the number of words using a dictionary. Here’s an example:
filename = 'myfile.txt' # replace with the name of your file
wordcount = {} # create an empty dictionary to store word counts
with open(filename, 'r') as file:
# read the contents of the file and split into words
words = file.read().split()
# iterate over each word and add to the word count dictionary
for word in words:
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
# print out the word count for each word
for word, count in wordcount.items():
print(word, count)
In this example, we first specify the name of the file to open (filename
). We then create an empty dictionary (wordcount
) to store the count of each word in the file.
We use a with
statement to open the file in read-only mode and read its contents into a variable (words
). We then split the contents of the file into individual words using the split()
method.
Next, we use a for
loop to iterate over each word in the words
list. If the word is not already in the wordcount
dictionary, we add it to the dictionary with a count of 1. If the word is already in the dictionary, we increment its count by 1.
Finally, we iterate over each key-value pair in the wordcount
dictionary and print out the word followed by its count.
In general, this approach can be used to count the frequency of any word or character in a text file using Python.