我正在尝试根据 SPARQL 查询的结果构建图表。出于查询构造的目的,我使用 SparqlWrapper 和 DBpedia 作为知识库。
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')
这输出
http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/2002/07/owl#Thing
还有更多的结果,但我正在寻找一种方法来从结果中构建一个图表,以便将它与现有的图表合并。
这给我一个错误
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
问题是输出 JSON 的值类似于这个链接