Skip to content

Instantly share code, notes, and snippets.

@pandwoter
Created October 13, 2020 10:55
Show Gist options
  • Save pandwoter/f83fbe44b51edb3ea3f7fc4fd6f71432 to your computer and use it in GitHub Desktop.
Save pandwoter/f83fbe44b51edb3ea3f7fc4fd6f71432 to your computer and use it in GitHub Desktop.
TOP K WORDS
def top_k_words(str, n)
return [] if n < 0
str = str.downcase.scan(/[\w']+/)
occurances = Hash.new
str.each do |word|
if occurances[word]
occurances[word] += 1
else
occurances[word] = 1
end
end
p occurances
occurances.sort.sort_by { |word, occurence| [-occurence, -word] }[0..n-1].map {|x| x[0]}.join(" ")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment