Skip to content

Instantly share code, notes, and snippets.

@jcemer
Last active December 16, 2015 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcemer/5400404 to your computer and use it in GitHub Desktop.
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
@ricardobeat
Copy link

A versão anterior dava pra traduzir 1:1 pra coffeescript, a segunda não :)

count_words = (text) ->
    return text.split(/\s+/).reduce (count, word) ->
        count[word] or= 0; count[word]++; count
    , {}

@ricardobeat
Copy link

underscore to the rescue:

count_words = (str) ->
    words = _(str.toLowerCase().split(/\s+/)).groupBy()
    _.object _(words).map (v, k) -> [k, v.length]

na real dá pra trapacear com ele:

count_words = (str) -> _(str.toLowerCase().split(/\s+/)).countBy()

O jashkenas praticamente portou o Ruby pra js

@jcemer
Copy link
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