欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【python】rdflib生成RDF,用sparql查询

程序员文章站 2022-03-04 13:01:27
...
# coding:utf-8

import rdflib

def create():
    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')
    * = 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, *))
    g.add((germany, located_in, europa))
    g.add((france, located_in, europa))
    g.add((china, located_in, asia))
    g.add((*, located_in, asia))
    ##############
    # c3,has,c4
    # c3,loc,p2
    g.serialize("graph.rdf")

def query():
    g = rdflib.Graph()
    g.parse("graph.rdf", format="xml")
    ################################
    # <a,?,?>
    q = "select ?relation ?part where { <http://www.example.org/country1> ?relation ?part}"
    x = g.query(q)
    t = list(x) ##### 二维
    # print(t[0][0])
    # http://www.example.org/has_border_with
    # print(t[0][1])
    # http://www.example.org/part1
    print(len(t))  #没有,则=0
    print(t[0])
    # <?,b,?>
    q = "select ?country ?part where {?country <http://www.example.org/located_in> ?part}"
    x = g.query(q)
    t = list(x)
    print(len(t))
    print(t[0])
    # <?,?,c>
    q = "select ?country ?relation where {?country ?relation <http://www.example.org/part1>}"
    x = g.query(q)
    t = list(x)
    print(len(t))
    print(t[0])
    ################################
    # <a,b,?>
    q = "select ?part where {<http://www.example.org/country1> <http://www.example.org/located_in> ?part}"
    x = g.query(q)
    t = list(x) ######二维: n*1
    print(len(t))
    # print(t[0][0])
    # http://www.example.org/part1
    print(t[0])
    # <a,?,c>
    # <?,a,b>

if __name__ == "__main__":
    create()
    query()

2,相关链接
https://blog.csdn.net/vuscity/article/details/79869828