Skip to content

Instantly share code, notes, and snippets.

@dogrunjp
Last active February 6, 2016 02:04
Show Gist options
  • Save dogrunjp/d738fc638c2e7a99b3dd to your computer and use it in GitHub Desktop.
Save dogrunjp/d738fc638c2e7a99b3dd to your computer and use it in GitHub Desktop.
VirtuosoにインポートしたRefex RDFから、gene reference idを引数にデータを取得するSPARQL及びラッパーアプリケーション。

ローカルに起てたVirtuosoにReFexのttlをインポートして、以下のようにスクリプトを呼び、jsonデータを表示しています。少し追記してサービスをたててD3.jsからAPIを呼んでもいいし、ファイル保存してもいいと思う。

python3 rdfutils.py 11657

ただし、 たぶんsparqlが良く無いと思うのですが、JSONの中に同じ値のハッシュが4つづつ入ってます。。。こ の箇所は、正しいspqrqlを教えていただけたらと思います。。。

from urllib.request import Request, urlopen
from urllib.parse import quote_plus
import sys
import json
argvs = sys.argv
q = argvs[1]
def getResult():
ENDPOINT = "http://localhost:8890/sparql"
sparql = " \
PREFIX refex: <http://refex.dbcls.jp/entry/> \
PREFIX refexo: <http://purl.jp/bio/01/refexo#> \
PREFIX dcterms: <http://purl.org/dc/terms/> \
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
SELECT ?refex ?sample_id ?organism ?expression_value \
WHERE { \
?refex rdfs:seeAlso <http://www.ncbi.nlm.nih.gov/gene/%s> ; \
refexo:refexSample ?sample ; \
refexo:expValue ?expression_value . \
?sample dcterms:identifier ?sample_id ; \
refexo:organism ?organism . \
} LIMIT 500 \
" % q
# python3よりURLエンコードはurllib.quote.plus()
sparql = quote_plus(sparql)
req = Request(ENDPOINT + "?query=" + sparql)
# レスポンスはデフォルトでXMLなので、
# JSONでデータを取得したいときは以下のようにrequest headerにメディアタイプを指定
req.add_header("Accept", "application/sparql-results+json")
res = urlopen(req)
result_str = res.read().decode('utf-8')
result_dic = json.loads(result_str)
print(result_dic["results"]["bindings"])
if __name__ == "__main__":
getResult()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment