【发布时间】:2009-09-16 01:32:32
【问题描述】:
我想分析我的数据库中的数据,以了解某些单词出现了多少次。 理想情况下,我想要一个特定列中使用的前 20 个单词的列表。 解决此问题的最简单方法是什么。
【问题讨论】:
标签: ruby-on-rails ruby
我想分析我的数据库中的数据,以了解某些单词出现了多少次。 理想情况下,我想要一个特定列中使用的前 20 个单词的列表。 解决此问题的最简单方法是什么。
【问题讨论】:
标签: ruby-on-rails ruby
创建一个自动激活的散列,然后遍历填充散列的行,并在每次获得相同的键(单词)时递增值。然后按值对哈希进行排序。
【讨论】:
我不确定您是否要问如何让 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
$
【讨论】:
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)
【讨论】: