如何计算单词中出现的字母频率" supercaliforniamightly"当用户在Ruby中输入类似的单词时,打印出星号或星号来计算出现的字母数量?
这是我的代码:
puts "Enter string: "
text= gets.chomp
text.downcase!
words = text.split(//)
frequencies = Hash.new(0)
words.each{|item| frequencies[item] +=1}
frequencies = frequencies.sort_by{ |item, amount| amount}
frequencies.reverse!
frequencies.each do |item, amount|
puts item + " " + amount.to_s
end
我想要的输出是这样的:
Enter a string:
uuuuiiii
u , 4 ****
i , 4 ****
答案 0 :(得分:3)
我稍微更改了输出(删除逗号前的空格),这样我就不会没有受过教育。
puts "Enter string: "
gets.chomp.downcase
.each_char.with_object(Hash.new(0)){|c, h| h[c] += 1}
.sort_by{|_, v| v}
.reverse
.each{|k, v| puts k + ", " + v.to_s + " " + "*" * v}
输出:
Enter string:
uuuuiiii
i, 4 ****
u, 4 ****