如何根据 Ruby 中的值拆分哈希?
我在 Ruby 中有一个散列,它存储字符串的词频,以词作为键,频率作为值。
words = a_string.split(/ /)
freqs = Hash.new(0)
words.each { |word| freqs[word] += 1 }
freqs = freqs.sort_by {|x,y| y }
freqs.reverse!
freqs.each do |word, freq|
puts word+' '+freq.to_s
end
我读过哈希迭代器以随机顺序返回哈希,但这似乎到目前为止都有效。
现在我需要 freqs 哈希以仅包含 20 个最常见的单词。我该怎么做?感谢您的阅读。
I have a hash in Ruby that is storing the word frequency of a string, with the word as the key and the frequency as the value.
words = a_string.split(/ /)
freqs = Hash.new(0)
words.each { |word| freqs[word] += 1 }
freqs = freqs.sort_by {|x,y| y }
freqs.reverse!
freqs.each do |word, freq|
puts word+' '+freq.to_s
end
I've read that hash iterators return the hash in a random order, but this seems to work so far.
Now I need to freqs hash to only contain the 20 most frequent words. How can I do this? Thanks for reading.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您可能已经看到的,它保持排序的原因是因为您调用 < code>Enumerable#sort_by 将您的
Hash
更改为Array
。从该方法的文档中:一旦你有了排序后的数组,你就可以使用
Array#first< /code>
获取前 20 名:
如果需要,您可以在结果上使用
to_hash
将其返回到Hash
,但它不会不再排序。As you've probably seen, the reason it stays sorted is because your call to
Enumerable#sort_by
changes yourHash
into anArray
. From the documentation for that method:Once you have your sorted array, you could just use
Array#first
to get the top 20:If you want, you could use
to_hash
on the result to return it back to aHash
, but it will no longer be sorted.