Advertisement
sawczakl

most frequent word

Jul 17th, 2023
1,693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | Source Code | 0 0
  1. # assuming you have already created a dictionary like this one
  2. # tallying word frequencies
  3.  
  4. d = {
  5.     'dog': 4,
  6.     'cat': 3,
  7.     'the': 3,
  8.     'chases': 2,
  9.     'why': 1
  10. }
  11.  
  12. # method 1
  13. # most Pythonic, but doesn't "show its work", so a leap of logic needed
  14. # use max to select the word that has the highest value directly
  15.  
  16. # this works by saying 'the key for determining max-ness is d.get,'
  17. # i.e. what we get when we look up the item in d, i.e. its value.
  18.  
  19. # easiest by far in Python but because of its compactness it may be
  20. # instructive to read the other methods
  21.  
  22. most_freq_word = max(d, key=d.get)
  23. print(most_freq_word)
  24.  
  25. # method 2
  26. # most intuitive
  27. # iterate through keys, keeping track of the highest value
  28.  
  29. highest_freq = 0
  30. most_freq_word = ''
  31. for word in d:
  32.     freq = d[word]
  33.     if freq > highest_freq:
  34.         most_freq_word = word
  35.         highest_freq = freq
  36. print(most_freq_word)
  37.  
  38. # method 3
  39. # invert the dictionary (swap values and keys)
  40. # then use max() to pick the highest value
  41.  
  42. # NOTE: because there can be ties, each new value needs to be a list;
  43. # here's what it would look like:
  44.  
  45. """
  46. d_inverted = {
  47.  4: ['dog'],
  48.  3: ['cat', 'the'],    # <-- note the tie here, hence the lists
  49.  2: ['chases'],
  50.  1: ['why']
  51. }
  52. """
  53.  
  54. d_inverted = {}
  55. for word in d:
  56.     freq = d[word]
  57.     if freq not in d_inverted:
  58.         d_inverted[freq] = []
  59.     d_inverted[freq].append(word)
  60.  
  61. highest_freq = max(d_inverted)
  62. most_freq_word = d_inverted[highest_freq][0] # [0] because it's a list
  63. print(most_freq_word)
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement