Created
September 21, 2015 07:23
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'open-uri' | |
require 'json' | |
module NDCLD | |
# NDCコードからラベルを取得するためのライブラリ | |
class NDC | |
SPARQL_ENDPOINT = "http://www.kanzaki.com/works/2015/ndc-ld/sparql" | |
attr_accessor :code | |
# NDCコードを受けとってインスタンスを作成する | |
def initialize(code_arg) | |
@code = code_arg.to_s | |
end | |
# NDCのラベルをNDC-LDから取得する | |
def label | |
query = <<-"EOS" | |
PREFIX ndc9: <http://id.ndl.go.jp/class/ndc9/> | |
PREFIX skos: <http://www.w3.org/2004/02/skos/core#> | |
SELECT ?label WHERE { | |
?s skos:notation "#{code}". | |
?s skos:prefLabel ?label. | |
FILTER langMatches(lang(?label), "JA") | |
} | |
EOS | |
response = search(query) | |
label = response.try(:[], "results").try(:[], "bindings").try(:map) {|b| b["label"]["value"]} | |
end | |
private | |
# SPARQLクエリをNDC-LDエンドポイントに投げる | |
def search(query) | |
params = Hash.new | |
params[:format] = :json | |
params[:query] = query | |
url = URI.encode([SPARQL_ENDPOINT, params.map{|k,v| [k,v].join("=") }.join("&")].join("?")) | |
response = JSON.parse(open(url).read.to_s) | |
end | |
end | |
end | |
# コマンドライン引数で指定したNDCコードに対応するラベルを出力 | |
if __FILE__ == $0 | |
ndc = NDCLD::NDC.new(ARGV[0]) | |
puts ndc.label | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NDC-LDが試験公開中の際に書いたコードです。現在は試験公開期間が終了したため使用できませんが、実用事例としてコードを公開いたします。