Python Sparql Querying Local File
我有以下 Python 代码。它基本上使用 SPARQL 从在线资源返回 RDF 的一些元素。
我想从我的一个本地文件中查询并返回一些内容。我尝试对其进行编辑,但无法返回任何内容。
为了在我的本地而不是 http://dbpedia.org/resource 中查询,我应该改变什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | from SPARQLWrapper import SPARQLWrapper, JSON # wrap the dbpedia SPARQL end-point endpoint = SPARQLWrapper("http://dbpedia.org/sparql") # set the query string endpoint.setQuery(""" PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX dbpr: <http://dbpedia.org/resource/> SELECT ?label WHERE { dbpr:Asturias rdfs:label ?label } """) # select the retur format (e.g. XML, JSON etc...) endpoint.setReturnFormat(JSON) # execute the query and convert into Python objects # Note: The JSON returned by the SPARQL endpoint is converted to nested Python dictionaries, so additional parsing is not required. results = endpoint.query().convert() # interpret the results: for res in results["results"]["bindings"] : print res['label']['value'] |
谢谢!
您可以使用以下命令查询 rdflib.graph.Graph():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | filename ="path/to/fileneme" #replace with something interesting uri ="uri_of_interest" #replace with something interesting import rdflib import rdfextras rdfextras.registerplugins() # so we can Graph.query() g=rdflib.Graph() g.parse(filename) results = g.query(""" SELECT ?p ?o WHERE { <%s> ?p ?o. } ORDER BY (?p) """ % uri) #get every predicate and object about the uri |
(a) 将本地 RDF 文件放在本地三元存储中,并将代码指向 localhost。 (b) 或者使用
1 2 3 4 | import rdflib.graph as g graph = g.Graph() graph.parse('filename.rdf', format='rdf') print graph.serialize(format='pretty-xml') |