问题
I am trying to construct a graph out of the results from SPARQL query. For the purpose of the query construction, I'm using SparqlWrapper and DBpedia as the knowledge base.
from SPARQLWrapper import SPARQLWrapper, JSON
from rdflib import Namespace, Graph, URIRef
from rdflib.namespace import RDF, FOAF
g = Graph()
name = "Asturias"
#labelName = URIRef("<http://dbpedia.org/resource/" + name +">")
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("""
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dbr: <http://dbpedia.org/resource/>
SELECT *
WHERE { dbr:Asturias ?predicate ?object }
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
predicate = result["predicate"]["value"]
object = result["object"]["value"]
print(name , predicate , object)
g.add((name, predicate, object))
print(len(g))
g.serialize(destination='./resources/testg.n3', format='n3')
This outputs
http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/2002/07/owl#Thing
and lot more results, but I'm looking for a way to construct a graph from the results, for it to be merged with existing graphs/'s.
This throws me an error as
in add
"Predicate %s must be an rdflib term" % (p,)
AssertionError: Predicate http://www.w3.org/1999/02/22-rdf-syntax-ns#type must be an rdflib term
The problem is the output JSON's value is something like this Link
来源:https://stackoverflow.com/questions/58519010/constructing-graph-using-rdflib-for-the-outputs-from-sparql-select-query-with