我一直在使用RDFLib解析数据并将其插入到三元组存储中。我遇到的一个常见问题是,在从链接的数据存储库中解析URL时,缺少尖括号将URL括起来。
要上传数据,我必须手动添加<和>,并使用URIRef重新创建URL。
我的方法有问题吗?有没有办法解析URL和尖括号?
代码如下:
#Querying the triplestore to retrieve all results
dbpediaSparqlEndpoint = 'http://dbpedia.org/sparql/'
sparql = SPARQLWrapper(dbpediaSparqlEndpoint)
dbpedia_query = 'PREFIX : <http://dbpedia.org/resource/> DESCRIBE :Benin'
dataGraph = Graph()
sparql.setQuery(dbpedia_query)
sparql.method = 'GET'
sparql.setReturnFormat(JSON)
output = sparql.query().convert()
# print list(output['results']['bindings'])
print type(output['results']['bindings'])
#Iterating through the output and adding the data to dataGraph
#First value is that of the index of the list
for index, value in enumerate(output['results']['bindings']):
#The encoding is necessary to parse non-English characters
test = value['s']['value'].encode('utf-8')
subj_raw = '<' + test + '>'
subj_refined = URIRef(subj_raw)
pred_raw = '<' + value['p']['value'].encode('utf-8') + '>'
pred_refined = URIRef(pred_raw)
if 'http' in value['o']['value']:
obj_raw = '<' + value['o']['value'].encode('utf-8') + '>'
obj_refined = URIRef(obj_raw)
else:
obj_raw = '"' + value['o']['value'].encode('utf-8') + '"'
obj_refined = URIRef(obj_raw)
dataGraph.add((subj_refined,pred_refined,obj_refined))发布于 2016-02-09 21:29:42
我认为直接将查询和更新结合起来可能会更好,我认为这样做不会有太多麻烦。我认为您将不能再使用describe,因为它的结果并未指定,但我认为您可以这样做:
insert {
?a ?b dbr:Berlin .
dbr:Berlin ?c ?d
}
where {
service <http://dbpedia.org/sparql> {
?a ?b dbr:Berlin .
dbr:Berlin ?c ?d .
}
}但是,如果您确实需要构造一些查询并从另一个源向其中注入值,那么您就应该使用准备好的查询。RDFlib supports prepared queries,以便您可以执行以下操作(文档中的示例):
initBindings kwarg可以用来传入初始绑定的字典:
Q= prepareQuery( 'SELECT ?s WHERE { ?person foaf:knows ?s.}‘,initNs ={ " FOAF ":FOAF }) g= rdflib.Graph() g.load("foaf.rdf") tim = rdflib.URIRef("http://www.w3.org/People/Berners-Lee/card#i") for row in g.query(q,initBindings={'person':tim}):打印行
您可以执行类似的操作,并使您的查询为:
INSERT DATA { ?s ?p ?o }并向其传递一个initBindings参数以填充?s ?p ?o值。
https://stackoverflow.com/questions/35283604
复制相似问题