How to get words frequency in efficient way with ruby?

前端 未结 7 1683
伪装坚强ぢ
伪装坚强ぢ 2021-02-05 17:50

Sample input:

\"I was 09809 home -- Yes! yes!  You was\"

and output:

{ \'yes\' => 2, \'was\' => 2, \'i\' => 1, \'home\         


        
7条回答
  •  野性不改
    2021-02-05 18:35

    This works but I am kinda new to Ruby too. There might be a better solution.

    def count_words(string)
      words = string.split(' ')
      frequency = Hash.new(0)
      words.each { |word| frequency[word.downcase] += 1 }
      return frequency
    end
    

    Instead of .split(' '), you could also do .scan(/\w+/); however, .scan(/\w+/) would separate aren and t in "aren't", while .split(' ') won't.

    Output of your example code:

    print count_words('I was 09809 home -- Yes! yes!  You was');
    
    #{"i"=>1, "was"=>2, "09809"=>1, "home"=>1, "yes"=>2, "you"=>1}
    

提交回复
热议问题