Python Lab · Experiment 33
Find the most frequent word in a text file
PythonWeek 7JNTUH R22 · CS206ES
Aim
To write a Python program that reads text from a file and finds the word that occurs the most number of times, ignoring upper and lower case and punctuation, and prints every word that shares the highest count if there is a tie.
Algorithm
- Read the file name. Open the file and read all its text. If the file does not exist, print an error and stop.
- Split the text into words at spaces and newlines.
- For each word, remove punctuation from both ends and change it to lower case. Skip it if nothing is left.
- Count each word in a dictionary: if the word is already a key, add 1 to its count, otherwise store it with count 1.
- If no words were found, print a message and stop.
- Find the highest count with
max()on the dictionary's values. - Collect all words whose count equals the highest count, sort them alphabetically, and print them with the count.
Program
import string
def count_words(text):
counts = {}
for token in text.split():
word = token.strip(string.punctuation).lower()
if word == "":
continue
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
file_name = input("Enter file name: ")
try:
with open(file_name, "r") as f:
text = f.read()
except FileNotFoundError:
print("Cannot open file", file_name)
else:
counts = count_words(text)
if not counts:
print("The file has no words")
else:
highest = max(counts.values())
winners = sorted(word for word in counts if counts[word] == highest)
print("Total words:", sum(counts.values()))
print("Different words:", len(counts))
if len(winners) == 1:
print(f"Most frequent word: '{winners[0]}' ({highest} times)")
else:
print(f"Tie: these words each occur {highest} times:", ", ".join(winners))Output
One word occurs the most
The cat sat on the mat.
The dog sat on the log!
"The end," said the cat.Enter file name: story.txt
Total words: 17
Different words: 9
Most frequent word: 'the' (6 times)A tie between words
Red apples, green apples.
Red cherries, green grapes.Enter file name: fruits.txt
Total words: 8
Different words: 5
Tie: these words each occur 2 times: apples, green, redRecorded by running this exact program. Typed input appears after each prompt.
How it works
Here a word is any group of characters between spaces or newlines, with punctuation such as . , ! " removed from both ends and changed to lower case. So The, the and "The all count as the word the. Punctuation inside a word is kept, so don't stays one word.
When several words share the highest count, the program prints all of them in alphabetical order. Picking just one of them would depend on the order of the words in the file, which is not a fair answer.
In the first run, the occurs 6 times (twice on each line), while cat, sat and on occur twice. In the second run, red, apples and green each occur twice, so there is a tie.
The collections.Counter class can do the counting in one line: Counter(words).most_common(1). The dictionary version is used here so that you can see how the counting works.
Common mistakes
Not changing words to lower case, so
Theandtheare counted as two different words.Splitting with
split(" ")instead ofsplit(). With an argument, newlines are not treated as separators and double spaces give empty strings;split()with no argument handles all whitespace.Writing
counts[word] += 1for a word that is not in the dictionary yet. This raisesKeyError; store the first count as 1 (or usecounts.get(word, 0) + 1).Using
max(counts)to find the most frequent word. On a dictionary,maxcompares the keys, so it returns the alphabetically last word, not the most common one.
Viva questions
Try to answer each one aloud before you open it.
Why is a dictionary a good choice for counting words?
Each word is a key and its count is the value. Checking whether a word is already a key and updating its count are both fast, even for long files.
What does max(counts.values()) return?
The largest value in the dictionary, which here is the highest number of times any word occurs.
What does the get() method of a dictionary do?
d.get(key, default)returns the value forkeyif it exists, anddefaultotherwise, without raisingKeyError. It allowscounts[w] = counts.get(w, 0) + 1.How can collections.Counter help in this program?
Counter(words)builds the word counts in one step, andmost_common(n)returns the n most frequent words with their counts.What is the difference between split() and split(" ")?
split()splits at any run of whitespace (spaces, tabs, newlines) and never gives empty strings.split(" ")splits at each single space only, so two spaces in a row give an empty string.