Skip to content

Instantly share code, notes, and snippets.

@jcemer
Last active December 16, 2015 07:39
Show Gist options
  • Select an option

  • Save jcemer/5400404 to your computer and use it in GitHub Desktop.

Select an option

Save jcemer/5400404 to your computer and use it in GitHub Desktop.
Count repeated words.
# it parses "a a a a b b b c c" to {"a"=>4, "b"=>3, "c"=>2}
# FROM
def self.estatisticas_do_texto(texto)
palavras = []
texto.split(' ').each do |word|
w = word.downcase.gsub(/\.|\,|\?|\!|\(|\)|\'/,'')
palavras << w
end
palavras.sort!
contador = {}
palavras.each do |p|
if contador.has_key?(p)
contador[p] += 1
else
contador.merge!(p => 1)
end
end
return contador
end
# TO
def count_repeated_words(str)
words = str.downcase.scan(/[\w-]+/).group_by(&:to_s)
words.merge(words) { |k, v| v.count }
end
@jcemer
Copy link
Copy Markdown
Author

jcemer commented Apr 17, 2013

haha, muito bom!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment