LoginSignup
7
4

More than 5 years have passed since last update.

不適切な言葉の検出にはantivirusが便利

Posted at

はじめに

プロフィールの文言なんかを更新すると、たまに出る「この文章には不適切な単語が含まれています」というやつ。

最近まで名前を知らなかったのだが、「profanity filter」(プロファニティ・フィルター)というらしい。

railsでprofanity filterを実装するgemがあったので紹介します。

インストール

Githubはこちら。
https://github.com/kami-zh/antivirus

Gemfile
gem 'antivirus'
bundle install

使い方

localeにprofane_words.ymlというymlを作る。

config/locales/profane_words.yml
ja:
  antivirus:
    message: に不適切な単語が含まれています
    profane_words:
      - xxx
      - yyy
      - zzz

profane_wordsのxxxなどのところに不適切な単語を書いてゆく。
不適切な単語は以下が参考になるかも。
http://monoroch.net/kinshi/

それで、modelのfilterをかけたいところにprofanity_filter: trueを記載するだけ。

app/models/user.rb
class User < ActiveRecord::Base
  validates :description, profanity_filter: true
end

そうすると、descriptionのバリデーションにひっかかる。
バリデーションメッセージはprofane_words.ymlに定義してる。

おわりに

profanity filter便利。

おそらく、文章を一致検索してるので速度などが気になると思いますが、filter適用前と適用後ではそこまで速度に違いがありませんでした。

注意点としては、profane_wordsを定義しすぎると、普通の文章なども不適切だと扱われてしまう、いわゆるフォルスポジティブが起こる。

なので、定義する時には文脈とか関係なく、使われていたら不適切だと思う単語を登録しましょう。

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4