【问题标题】:Best way to analyse data using ruby使用 ruby​​ 分析数据的最佳方法
【发布时间】:2009-09-16 01:32:32
【问题描述】:

我想分析我的数据库中的数据,以了解某些单词出现了多少次。 理想情况下,我想要一个特定列中使用的前 20 个单词的列表。 解决此问题的最简单方法是什么。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    创建一个自动激活的散列,然后遍历填充散列的行,并在每次获得相同的键(单词)时递增值。然后按值对哈希进行排序。

    【讨论】:

      【解决方案2】:

      字数计数器...

      我不确定您是否要问如何让 rails 来处理这个问题或如何计算字数,但我还是继续做了一个面向列的 ruby​​ wordcounter。

      (顺便说一句,一开始我确实尝试了 autovivified 哈希,这是一个很酷的技巧。)


      # col: a column name or number
      # strings: a String, Array of Strings, Array of Array of Strings, etc.
      def count(col, *strings) 
        (@h ||= {})[col = col.to_s] ||= {}
        [*strings].flatten.each { |s|
          s.split.each { |s|
            @h[col][s] ||= 0
            @h[col][s]  += 1
          }
        }
      end
      def formatOneCol a
        limit = 2
        a.sort { |e1,e2| e2[1]<=>e1[1] }.each { |results|
          printf("%9d %s\n", results[1], results[0])
          return unless (limit -= 1) > 0
        }
      end
      def formatAllCols
        @h.sort.each { |a|
          printf("\n%9s\n", "Col " + a[0])
          formatOneCol a[1]
        }
      end
      
      count(1,"how now")
      count(1,["how", "now", "brown"])
      count(1,[["how", "now"], ["brown", "cow"]])
      count(2,["you see", "see you",["how", "now"], ["brown", "cow"]])
      count(2,["see", ["see", ["see"]]])
      count("A_Name Instead","how now alpha alpha alpha")
      
      formatAllCols
      

      $ ruby count.rb
      
          Col 1
              3 how
              3 now
      
          Col 2
              5 see
              2 you
      
      Col A_Name Instead
              3 alpha
              1 how
      $ 
      

      【讨论】:

        【解决方案3】:

        digitalross 的答案对我来说也太冗长了,因为你标记了 ruby​​-on-rails 并说你使用 DB.. 我假设你需要一个 activerecord 模型,所以我给你一个完整的解决方案

        在您的模型中:

        def self.top_strs(column_symbol, top_num)
          h = Hash.new(0)
          find(:all, :select => column_symbol).each do |obj|
            obj.send(column_symbol).split.each do |word|
              h[word] += 1
            end
          end
        
          h.map.sort_by(&:second).reverse[0..top_num]
        end
        

        例如模型评论、列体:

        Comment.top_strs(:body, 20)
        

        【讨论】:

        • 谢谢,看起来是一个更好的解决方案。使用它时遇到的问题如下: ArgumentError:sort_by 调用中的参数数量错误(1 代表 0)。另外,传递给它的 :second 符号是什么?
        • 我用这个修复了它:ph.sort_by {|a,b| b}.reverse[0..top_num]
        • 应该是 "sort_by(&:second)" - 这是 proc 的符号,你可以在这里了解它:blog.hasmanythrough.com/2006/3/7/symbol-to-proc-shorthand
        猜你喜欢
        • 1970-01-01
        • 2010-11-16
        • 1970-01-01
        • 1970-01-01
        • 2022-07-25
        • 2012-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多