Ruby &引用;WordScont“;返回字母而不是单词?

Ruby &引用;WordScont“;返回字母而不是单词?,ruby,word-count,Ruby,Word Count,我一直在想为什么wordscont返回字母而不是单词,但我不知道原因 示例测试用例: count_words("A man, a plan, a canal -- Panama") # => {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1} count_words "Doo bee doo bee doo" # => {'doo' => 3, 'bee' =>

我一直在想为什么
wordscont
返回字母而不是单词,但我不知道原因

示例测试用例:

count_words("A man, a plan, a canal -- Panama")
# => {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1}

count_words "Doo bee doo bee doo"
# => {'doo' => 3, 'bee' => 2}
代码如下:

class WordCount

  def count_words(string)
    changed = string.downcase.gsub(/[^a-zA-Z]/,"")
    words = changed.split("")
    counts = Hash.new(0)
    words.each {|x| counts [x] += 1;}
    return counts
  end

end


test = WordCount.new
a = test.count_words("A man, a plan, a canal -- Panama")
b = test.count_words "Doo bee doo bee doo"
puts a
puts b

如果要计算实际单词数(例如,“--”不计算为单词):


我已经简化了你的方法,现在它计算了单词:

def count_words(string)
   words = string.downcase.gsub(/[^a-zA-Z\s]/,"").split( /\s+/ )
   words.reduce({}) {| h,x | h[x] ||= 0; h[x] += 1;h }
end

count_words("A man, a plan, a canal -- Panama")
# => {"a"=>3, "man"=>1, "plan"=>1, "canal"=>1, "panama"=>1}
注意:不要在大括号前加空格
[

  • gsub(/[^a-zA-Z]/,”)
    删除所有非字母字符
  • split(“”)
    按每个字符拆分字符串

WordCount\count\u words
返回一个将字符映射为整数的哈希值。有什么问题吗?只返回:
counts.keys.size
它应该返回count每个单词而不是字母,当我运行测试文件时,它会计算字母数。@user32212117是否需要使用(word->count)返回他
哈希值配对?如果是,你已经做了这个=)这些例子是想要的,还是实际的行为?如果是想要的,实际的是什么?如果是实际的,它们有什么不同?天哪!非常感谢你,因为我的拆分中没有/\s+/!
def count_words(string)
   words = string.downcase.gsub(/[^a-zA-Z\s]/,"").split( /\s+/ )
   words.reduce({}) {| h,x | h[x] ||= 0; h[x] += 1;h }
end

count_words("A man, a plan, a canal -- Panama")
# => {"a"=>3, "man"=>1, "plan"=>1, "canal"=>1, "panama"=>1}