python SPARQLWrapper 知识图谱 操作接口 jena-fuseki

代码:

1
2
3
4
5
6
7
8
9
10
11
12
#导入包
from SPARQLWrapper import SPARQLWrapper, JSON
#创建query和update对象,以便进行各种操作
#XXX是数据库的名字
query = SPARQLWrapper("http://localhost:3030/XXX/query")
update = SPARQLWrapper("http://localhost:3030/XXX/update")
#这两句很关键
query.setReturnFormat(JSON)
update.setMethod('POST')
#远程操作
query.query().convert()
update.query()
举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
update = SPARQLWrapper("http://localhost:3030/xxx/update")
update.setMethod('POST')
#setQuery里面的内容就是原始命令的字符串形式(当然,注释形式也可)
update.setQuery(
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
+ "PREFIX ex: <http://example.org/>"
+ "PREFIX zoo: <http://example.org/zoo/>"
+ "PREFIX owl: <http://www.w3.org/2002/07/owl#>"

+ "DELETE DATA {"
+ "ex:dog1 rdf:type ex:animal ."
+ "ex:cat1 rdf:type ex:cat ."
+ "ex:cat rdfs:subClassOf ex:animal ."
+ "zoo:host rdfs:range ex:animal ."
+ "ex:zoo1 zoo:host ex:cat2 ."
+ "ex:cat3 rdf:sameAs ex:cat2 ."
+ "}"
)
update.query()