Mae向きなブログ

Mae向きな情報発信を続けていきたいと思います。

mecab-ruby

mecab-rubyのインストール

$ ruby extconf.rb
$ make
% sudo make install

mecab-rubyの今日時点の最新バージョンは、0.97で、最初、これをインストールしようと思ったのですが、mecabのバージョンとそろえる必要があるみたいです。

mmasa@debian:~/$ mecab -v
mecab of 0.93

なので、mecab-ruby-0.93をダウンロードして、インストール作業を行いました。

MeCabで遊んでみる

http:/localhost/.../word_freq.rb?url=http://d.hatena.ne.jp/rahaema/
な感じで実行すると、MeCabを使って、Web上でよく使われている単語を取り出すようなCGIを作ってみました。

まずは、実行結果です。

日記, 8
拡張, 7
研修, 20
作成, 14
エントリー, 14
以下, 11
ライブラリ, 7
ヶ月, 19
インストール, 8
マーク, 16
ブック, 16

word_freq.rb

#!/usr/bin/ruby -Ke

require 'cgi'
require 'open-uri'
require 'nkf'
require 'MeCab'

Reg_kanji_katakana = 
  Regexp::compile("[\xb0\xa1-\xf4\xa4\xa1\xbc\xa5\xa1-\xa5\xf6]", nil, 'e')

def get_freq(url)
  freq_word = Hash.new(0)
  open(url) do |f|
    if f.content_type == "text/html"
      content =  NKF.nkf("-e -m0", f.read)
      content.gsub!(/[\x00-\x7f]/, '')
      c = MeCab::Tagger.new("-Ochasen")
      n = c.parseToNode(content)
      while n do
        token = n.surface
        hinshi = n.feature.split(/,/)[0]
        if hinshi == "\xcc\xbe\xbb\xec"
          if ((token =~ Reg_kanji_katakana) && (token.length > 2))
            freq_word[token] += 1
          end
        end
        n = n.next
      end
    end
  end
  return freq_word
end

cgi = CGI.new
url = cgi.params['url'][0]
hash = get_freq(url)

puts cgi.header("type" => "text/html", "charset" => "euc-jp")
hash.each do |key, value|
  print "#{key}, #{value}<br>" if value >= 5 # 5回以上出現する単語のみ
end