gpt4 book ai didi

python - 使用 RDFLib 时处理缺少 <> 封闭 URL

转载 作者:太空宇宙 更新时间:2023-11-04 10:16:13 28 4
gpt4 key购买 nike

我一直在使用 RDFLib 来解析数据并将其插入到三元组中。我遇到的一个常见问题是,从关联数据存储库解析时,没有尖括号括起 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))

最佳答案

我认为直接合并您的查询和更新可能会更好,我认为您可以轻松完成。我认为您将无法再使用 describe,因为它的结果未指定,但我认为您可以这样做:

insert {
?a ?b dbr:Berlin .
dbr:Berlin ?c ?d
}
where {
service <http://dbpedia.org/sparql> {
?a ?b dbr:Berlin .
dbr:Berlin ?c ?d .
}
}

但是,如果您确实需要构建一些查询并从其他来源向它们注入(inject)值,那么您应该使用准备好的查询RDFlib supports prepared queries ,以便您可以执行以下操作(文档中的示例):

The initBindings kwarg can be used to pass in a dict of initial bindings:

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}):
print row

您可以做类似的事情并让您的查询:

INSERT DATA { ?s ?p ?o }

并向其传递一个 initBindings 参数以填充 ?s ?p ?o 值。

关于python - 使用 RDFLib 时处理缺少 <> 封闭 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35283604/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com