0

我一直在使用下面的代码来使用 Ruby 查找字符串中给定单词的频率。我的问题是如何调整它以在给定时间找到 2 个单词的频率。例如:“咩咩咩黑羊”应该返回......

{"baa baa"=>2, "baa black"=>1, "black sheep"=>1}  

代码:

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

2 回答 2

1
str = "baa baa baa black sheep"

count = Hash.new(0)
str.split.each_cons(2) do |words|
  count[ words.join(' ') ] += 1
end
count
# => {"baa baa"=>2, "baa black"=>1, "black sheep"=>1}
于 2013-04-10T00:14:21.477 回答
0
def count_words(string)
  words = string.downcase.split(' ')
  frequency = Hash.new(0)
  while words.size >= 2
    frequency["#{words[0]} #{words[1]}"] += 1
    words.shift
  end
  frequency
end
于 2013-04-10T00:02:55.240 回答