我是Ruby的新手,正在尝试编写一种将返回字符串中最常见单词的数组的方法。如果有一个单词的计数很高,则应返回该单词。如果有两个单词用于高计数,则应将两个单词都以数组形式返回。
问题是,当我通过第二个字符串时,代码仅将“单词”计数两次,而不是三次。传递第三个字符串时,它返回的计数为2的“ it”,这没有意义,因为“ it”的计数应为1。
def most_common(string)
counts = {}
words = string.downcase.tr(",.?!",'').split(' ')
words.uniq.each do |word|
counts[word] = 0
end
words.each do |word|
counts[word] = string.scan(word).count
end
max_quantity = counts.values.max
max_words = counts.select { |k, v| v == max_quantity }.keys
puts max_words
end
most_common('a short list of words with some words') #['words']
most_common('Words in a short, short words, lists of words!') #['words']
most_common('a short list of words with some short words in it') #['words', 'short']
您计算单词实例数的方法就是您的问题。it
在中with
,因此需要重复计算。
[1] pry(main)> 'with some words in it'.scan('it')
=> ["it", "it"]
不过,可以更轻松地完成操作,您可以使用each_with_object
调用按值实例的数量将数组的内容分组,如下所示:
counts = words.each_with_object(Hash.new(0)) { |e, h| h[e] += 1 }
这遍历数组中的每个条目,并为哈希中每个单词的条目的值加1。
因此,以下内容将为您工作:
def most_common(string)
words = string.downcase.tr(",.?!",'').split(' ')
counts = words.each_with_object(Hash.new(0)) { |e, h| h[e] += 1 }
max_quantity = counts.values.max
counts.select { |k, v| v == max_quantity }.keys
end
p most_common('a short list of words with some words') #['words']
p most_common('Words in a short, short words, lists of words!') #['words']
p most_common('a short list of words with some short words in it') #['words', 'short']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句