Return the k most frequent words in a log by count
Write a function topKWords(log, k) that analyzes a given log file content and identifies the top K most frequently occurring words within it. The function should return an array containing these top K words, sorted by their frequency of occurrence in descending order. Counting words for top K frequent words is easiest with a Map.
For instance, given a log:
May 12, 2023: User1 logged in.
May 13, 2023: User2 logged in.
May 13, 2023: User1 performed an action.
May 14, 2023: User3 logged in.
May 15, 2023: User2 performed an action.
May 15, 2023: User1 logged out.
And a value of K = 3, the function topKWords(log, 3) should return:
['User1', 'logged', 'May']
This output represents the top 3 most frequently occurring words in the log, which are ‘User1’, ‘logged’, and ‘May’ in this example.
The function should process the log content to count word occurrences, then sort and return the most frequent words up to the specified limit of K.