Skip to content
Laviyx Learn

Try

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

  1. Read the file name. Open the file and read all its text. If the file does not exist, print an error and stop.
  2. Split the text into words at spaces and newlines.
  3. For each word, remove punctuation from both ends and change it to lower case. Skip it if nothing is left.
  4. Count each word in a dictionary: if the word is already a key, add 1 to its count, otherwise store it with count 1.
  5. If no words were found, print a message and stop.
  6. Find the highest count with max() on the dictionary's values.
  7. Collect all words whose count equals the highest count, sort them alphabetically, and print them with the count.

Program

Python
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

Input file: story.txt (Text)
The cat sat on the mat.
The dog sat on the log!
"The end," said the cat.
Output 1
Enter file name: story.txt
Total words: 17
Different words: 9
Most frequent word: 'the' (6 times)

A tie between words

Input file: fruits.txt (Text)
Red apples, green apples.
Red cherries, green grapes.
Output 2
Enter file name: fruits.txt
Total words: 8
Different words: 5
Tie: these words each occur 2 times: apples, green, red

Recorded 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 The and the are counted as two different words.

  • Splitting with split(" ") instead of split(). 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] += 1 for a word that is not in the dictionary yet. This raises KeyError; store the first count as 1 (or use counts.get(word, 0) + 1).

  • Using max(counts) to find the most frequent word. On a dictionary, max compares 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 for key if it exists, and default otherwise, without raising KeyError. It allows counts[w] = counts.get(w, 0) + 1.

  • How can collections.Counter help in this program?

    Counter(words) builds the word counts in one step, and most_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.

Learn the concepts

All Python Programming Lab experiments →