Skip to content

Instantly share code, notes, and snippets.

@jcemer jcemer/gist:5400404
Last active Dec 16, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Apr 17, 2013

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

This comment has been minimized.

Copy link

commented Apr 17, 2013

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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.