How to get words frequency in efficient way with ruby?

前端 未结 7 1679
伪装坚强ぢ
伪装坚强ぢ 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:30

    This code will ask you for input and then find the word frequency for you:

        puts "enter some text man"
    text = gets.chomp
    words = text.split(" ")
    frequencies = Hash.new(0)
    words.each { |word| frequencies[word.downcase] += 1 }
    frequencies = frequencies.sort_by {|a, b| b}
    frequencies.reverse!
    frequencies.each do |word, frequency|
        puts word + " " + frequency.to_s 
    end
    

提交回复
热议问题