Last active
December 16, 2015 07:39
-
-
Save jcemer/5400404 to your computer and use it in GitHub Desktop.
Count repeated words.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
haha, muito bom!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A versão anterior dava pra traduzir 1:1 pra coffeescript, a segunda não :)