Yahoo! WebサービスAPIサンプル(テキスト解析)

概要


Yahoo!WebサービスAPIのテキスト解析のサンプルです。
YahooのWebサービスAPIを利用するにはIDが必要です。以下のサイトからIDを取得することができます。
(Yahoo!IDを事前に取得していること。無料)
http://developer.yahoo.co.jp/jlp/MAService/V1/pars...

サンプルページ


指定された文章を解析し、表記、読みがな、品詞をそれぞれ表示します。
http://sakura-computer.co.jp/webservice/yahoo/mase...

参考文献・リンク


CGIライブラリのリファレンスマニュアル
REXMLについて(日本語リファレンスマニュアル)

ソースコード


#!/usr/local/bin/ruby

require "cgi"
require "open-uri"
require "rexml/document"
require "pp"

begin
  cgi = CGI.new('html4Tr')
  html = "解析できませんでした。"
  credit = "<!-- Begin Yahoo! JAPAN Web Services Attribution Snippet -->
<a href='http://developer.yahoo.co.jp/about'><img src='http://i.yimg.jp/images/yjdn/yjdn_attbtn1_125_17.gif' title='Webサービス by Yahoo! JAPAN' alt='Web Services by Yahoo! JAPAN' width='125' height='17' border='0' style='margin:15px 15px 15px 15px'></a>
<!-- End Yahoo! JAPAN Web Services Attribution Snippet -->"


  #センテンスが入力されているときのみ処理を行う。
  if cgi["sentence"] != "" then
    
    query = "http://api.jlp.yahoo.co.jp/MAService/V1/parse?appid=取得したアプリケーションID&sentence=" + CGI.escape(cgi["sentence"]) + "&result=ma"
    xml = REXML::Document.new(open(query))
    
    #検索結果を確認し、結果HTMLを作成する。
    if xml.elements["ResultSet/ma_result/total_count"] != 0 then
      html = "<table border=1>"
      html += "<tr bgcolor=gray><td>表記</td><td>読みがな</td><td>品詞</td></tr>"
      xml.elements.each("ResultSet/ma_result/word_list/word") { |word|
        html += "<td>" + word.elements["surface"].text + "</td>"
        html += "<td>" + word.elements["reading"].text + "</td>" 
        html += "<td>" + word.elements["pos"].text + "</td>"
        html += "</tr>"
      }
      html += "</table>"
    end
  end

  #ページの作成
  title = "Yahoo!日本語形態素解析APIサンプル " + cgi["sentence"]
  cgi.out do
    cgi.html do
      cgi.head { cgi.title { title } } + cgi.body do
        cgi.h3 { "Yahoo!WebサービスAPIサンプル(日本語形態素解析)" } + 
          "解析したいセンテンスを入力してボタンをクリックしてください。" +
          cgi.form do
          cgi.text_field("sentence", cgi["sentence"]) +
            cgi.br +
            cgi.submit
        end +
          cgi.h3 { "解析結果" } + html + cgi.br + credit
      end
    end
  end
  
#例外処理
rescue => ex
  print cgi.header
  puts '<pre>' + ex + '</pre>'
  puts '<pre>'
  pp ex.backtrace
  puts '</pre>'
  puts '<pre>'
  pp query
  puts '</pre>'
end
2008年02月21日(木) 20:31:22 Modified by y_tabira




スマートフォン版で見る