Skip to content

Instantly share code, notes, and snippets.

@blankdots
Last active January 30, 2017 18:04
Show Gist options
  • Save blankdots/503adb76c5970d4dea68ea5281f0a392 to your computer and use it in GitHub Desktop.
Save blankdots/503adb76c5970d4dea68ea5281f0a392 to your computer and use it in GitHub Desktop.
template for construct and select to rdflib
from rdflib import ConjunctiveGraph, URIRef, Literal
from SPARQLWrapper import SPARQLWrapper, JSON
# import json
#http://rdfextras.readthedocs.io/en/latest/working_with.html
graph = ConjunctiveGraph()
sparql = SPARQLWrapper("http://localhost:3030/ds/query")
# add a default graph, though that can also be in the query string
sparql.addDefaultGraph("http://data.hulib.helsinki.fi/attx/ids")
sparql.addDefaultGraph("http://data.hulib.helsinki.fi/attx/work1")
sparql.setQuery("""CONSTRUCT {?subject a ?object} WHERE { ?subject a ?object } LIMIT 25""")
try:
# ret = sparql.query() # this is an array consisting of "subj", "o", "opt"
# sparql.setReturnFormat(JSON)
data = sparql.query().convert()
graph.parse(data=data.serialize(), format='xml')
# for row in data["results"]["bindings"]:
# print row
# if row['object']['type'] == 'uri':
# graph.add((URIRef(row['subject']['value']), URIRef(row['predicate']['value']), URIRef(row['object']['value'])))
# elif row['object']['type'] == 'literal':
# graph.add((URIRef(row['subject']['value']), URIRef(row['predicate']['value']), Literal(row['object']['value'])))
except Exception as error:
print error
print graph.serialize(format='turtle')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment