通过语句相似度过滤垃圾评论
研究相似度有2种方式, Levenshtein distance 以及 How to Strike a Match . 最后使用了后者计算相似度的方式实现了一个简单的评论过滤系统.
代码实现
text这个gem 同时提供了以上两种算法. 有兴趣的可以看一下源码中两种算法的具体实现.
Comment 中验证评论是否合法
class Comment < ActiveRecord::Base ... validate :check_spam ... def check_spam #遍历检查 spam 中条目与评论的相似度, 如果大于设定比例则添加 error, 验证失败 Spam.all.each do |spam| if Text::WhiteSimilarity.new.similarity(body, spam.body) > (spam.similarity || 0.9) errors.add(:body, "内容不合法") return end end # 对于 spam 中没有收录的模板或漏网之鱼的新评论检查与最近的3条评论的相似度 # 如果相似度大于95%则过滤, 一般垃圾评论都是连续刷评论的. new_record? and Comment.last(3).each do |comment| if Text::WhiteSimilarity.new.similarity(body, comment.body) > 0.95 errors.add(:body, "内容不合法") return end end end end