COTOHA API Portal の使用例です。
parsing.rb
#! /usr/bin/ruby
# -*- encoding: utf-8 -*-
#
# parsing.rb
#
# Feb/27/2020
#
# ---------------------------------------------------------------------
require 'faraday'
require 'json'
#
load 'get_config.rb'
load 'get_token.rb'
# ---------------------------------------------------------------------
STDERR.puts "*** 開始 ***"
#
config = get_config_proc()
#
access_token = get_token_proc(config)
#
sentence = "特急はくたか"
#
headers={
"Content-Type": "application/json",
"Authorization": "Bearer " + access_token
}
#
data = {
"sentence": sentence,
"type": "default"
}
str_json = JSON.generate(data)
#
url = config['url_base'] + "v1/parse"
#
con = Faraday.new
res = con.post do |req|
req.url url
req.headers = headers
req.body = str_json
end
#
puts res.status
dict_aa=JSON.parse(res.body)
#
dict_aa['result'].each {|unit|
unit['tokens'].each {|token|
str_out = token['form'] + "\t" + token['pos']
puts str_out
}
}
#
STDERR.puts "*** 終了 ***"
# ---------------------------------------------------------------------
get_config.rb
# -*- encoding: utf-8 -*-
#
# get_config.rb
#
# Feb/27/2020
#
# ---------------------------------------------------------------------
require 'dotenv'
#
# ---------------------------------------------------------------------
def get_config_proc()
Dotenv.load
config = {}
config["grantType"] = "client_credentials"
config["clientId"] = ENV["CLIENT_ID"]
config["clientSecret"] = ENV["CLIENT_SECRET"]
config["url_publish"] = ENV['ACCESS_TOKEN_PUBLISH_URL']
config["url_base"] = ENV['DEVELOPER_API_BASE_URL']
#
return config
end
# ---------------------------------------------------------------------
get_token.rb
# -*- encoding: utf-8 -*-
#
# get_token.rb
#
# Feb/27/2020
#
# ---------------------------------------------------------------------
require 'faraday'
require 'json'
#
# ---------------------------------------------------------------------
def get_token_proc(config)
str_json = JSON.generate(config)
#
headers={
"Content-Type": "application/json"
}
#
con = Faraday.new
res = con.post do |req|
req.url config['url_publish']
req.headers['Content-Type'] = 'application/json'
req.body = str_json
end
#
dict_aa=JSON.parse(res.body)
access_token = dict_aa['access_token']
#
return access_token
end
# ---------------------------------------------------------------------
実行結果
$ ./parsing.rb
*** 開始 ***
200
特急 名詞
は 動詞語幹
く 動詞接尾辞
たか 名詞
*** 終了 ***