【问题标题】:"wordscount" returns letters instead of words? [closed]“wordscount”返回字母而不是单词? [关闭]
【发布时间】:2014-02-05 22:03:40
【问题描述】:

我一直想弄清楚为什么wordscount返回的是字母而不是单词,但我不知道原因。

示例测试用例:

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

【问题讨论】:

  • WordCount#count_words 返回一个将字符映射为整数的哈希值。有什么问题?
  • 只返回:counts.keys.size
  • 它应该返回计算每个单词而不是字母,当我运行测试文件时,它会计算字母。
  • @user3221217 你需要用(word -> count)对返回Hash吗?如果是,你已经这样做了 =)
  • 这些示例是期望的还是实际的行为?如果是想要的,那实际的又是什么呢?如果那是实际的,它们有何不同?

标签: ruby word-count


【解决方案1】:
  • gsub(/[^a-zA-Z]/,"") 删除所有非字母字符。
  • split("") 按每个字符分割字符串。

【讨论】:

    【解决方案2】:

    如果你想统计实际的字数(例如,'--' 不计为一个字):

    class WordCount
      def count_words(string)
        words = string.scan(/\w+/).group_by(&:downcase)
        Hash[*words.flat_map { |w,a| [w,a.size] }]
      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 # => {"a"=>3, "man"=>1, "plan"=>1, "canal"=>1, "panama"=>1}
    puts b # => {"doo"=>3, "bee"=>2}
    

    【讨论】:

      【解决方案3】:

      我已经简化了你的方法,现在可以计算字数了:

      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}
      

      注意:不要在大括号[前加空格。

      【讨论】:

      • 天啊!非常感谢,因为我的拆分中没有 /\s+/ !
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 2018-08-03
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多