Most Frequent Word in a Document

Medium ⏱ 12 min 49% acceptance ★★★★☆ 4.2
Write top_word(path) returning the most frequent word in a text file, case-insensitive, with words split on whitespace and stripped of .,!?;: punctuation at the ends. Ties may break arbitrarily. Return None for an empty file.

Examples

Example 1
Input
top_word('essay.txt')  # 'The cat saw the dog. The dog ran.'
Output
'the'
Explanation

'the' appears three times, beating dog's two.

Constraints

  • Case-insensitive counting.
  • Strip .,!?;: from word edges.
  • None for no words.

Topics

File Handlingaggregation

Companies

GoogleAdobeInfosys

Hints

Hint 1

A plain dict (or collections.Counter) tallies counts.

Hint 2

max(counts, key=counts.get) finds the winner.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.