您的位置:首页 > 其它

利用RDFLib的SPARQL进行查询的一个例子

2015-10-09 10:26 603 查看
利用RDFLib的SPARQL进行查询的一个例子

该例子实现如下功能:

1. Import RDFLib.

2. 创建一个简单的graph(包含2到4个关系)

3. 将graph以rdf格式写入文件(Graph.serialize)

4. 从文件中读取graph

5.利用SPARQL从graph中提取信息(Graph.parse)

import rdflib

g = rdflib.Graph()
has_border_with = rdflib.URIRef('http://www.example.org/has_border_with')
located_in = rdflib.URIRef('http://www.example.org/located_in')

germany = rdflib.URIRef('http://www.example.org/country1')
france = rdflib.URIRef('http://www.example.org/country2')
china = rdflib.URIRef('http://www.example.org/country3')
mongolia = rdflib.URIRef('http://www.example.org/country4')

europa = rdflib.URIRef('http://www.example.org/part1')
asia = rdflib.URIRef('http://www.example.org/part2')

g.add((germany,has_border_with,france))
g.add((china,has_border_with,mongolia))
g.add((germany,located_in,europa))
g.add((france,located_in,europa))
g.add((china,located_in,asia))
g.add((mongolia,located_in,asia))

q = "select ?country where { ?country <http://www.example.org/located_in> <http://www.example.org/part1> }"
x = g.query(q)
print list(x)
# write graph to file, re-read it and query the newly created graph
g.serialize("graph.rdf")
g1 = rdflib.Graph()
g1.parse("graph.rdf", format="xml")
x1 = g1.query(q)
print list(x1)


Reference

1. http://stackoverflow.com/questions/16829351/is-there-a-hello-world-example-for-sparql-with-rdflib
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: