我正在创建一个本体,我想从dbpedia
添加数据。例如,我想添加有关瑞士的数据。
这就是我在做的事。
g = Graph()
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
query = """
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbpedia: <http://dbpedia.org/resource/>
PREFIX dbp: <http://dbpedia.org/property/>
PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
SELECT DISTINCT ?s ?pop ?code
WHERE{
?s rdf:type dbo:PopulatedPlace.
?s dbp:iso3166code ?code.
?s dbo:populationTotal ?pop.
FILTER (?s = dbpedia:Switzerland)
}
"""
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
然后我将我提取的信息添加到我的图表中
for result in results["results"]["bindings"]:
N = int(result["pop"]["value"])
totPopulation = Literal(N)
g.add(( cName, RDF.type, dbo.Country))
g.add(( cName, dbo.populationTotal, totPopulation ))
g.add(( cName, dbp.iso3166code, Literal(str(result["code"]["value"])) ))
有没有更简单的方法呢?
答案 0 :(得分:3)
使用SPARQL CONSTRUCT
查询可能会更容易,因为此查询类型返回一组本机RDF三元组:
from rdflib import Graph
from SPARQLWrapper import SPARQLWrapper, RDF
# create empty graph
g = Graph()
# execute SPARQL CONSTRUCT query to get a set of RDF triples
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.addDefaultGraph("http://dbpedia.org")
query = """
PREFIX dbpedia: <http://dbpedia.org/resource/>
CONSTRUCT {
?s rdf:type dbo:PopulatedPlace.
?s dbp:iso3166code ?code.
?s dbo:populationTotal ?pop.
} WHERE{
?s rdf:type dbo:PopulatedPlace.
?s dbp:iso3166code ?code.
?s dbo:populationTotal ?pop.
FILTER (?s = dbpedia:Switzerland)
}
"""
sparql.setQuery(query)
try :
sparql.setReturnFormat(RDF)
results = sparql.query()
triples = results.convert() # this converts directly to an RDFlib Graph object
except:
print "query failed"
# add triples to graph
g += triples