python中用rdflib生成rdf,用sparql查询

根据原作者:利用RDFLib的SPARQL进行查询的一个例子进行了改写。
其他资料:
rdflib中SPARQL如何判断得到的结果为空
使用 SPARQL 查询 RDF
Python RDF知识库查询

接下来,上我的代码~ 其实,根据三元组的模式

# 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')
    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))
    ##############
    # c3,has,c4
    # c3,loc,p2
    g.serialize("graph.rdf")

def query():
    g = rdflib.Graph()
    g.parse("graph.rdf", format="xml")
    ################################
    # 
    q = "select ?relation ?part where {  ?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])
    # 
    q = "select ?country ?part where {?country  ?part}"
    x = g.query(q)
    t = list(x)
    print(len(t))
    print(t[0])
    # 
    q = "select ?country ?relation where {?country ?relation }"
    x = g.query(q)
    t = list(x)
    print(len(t))
    print(t[0])
    ################################
    # 
    q = "select ?part where {  ?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])
    # 
    # 

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

graph.rdf:


<rdf:RDF
   xmlns:ns1="http://www.example.org/"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
>
  <rdf:Description rdf:about="http://www.example.org/country3">
    <ns1:located_in rdf:resource="http://www.example.org/part2"/>
    <ns1:has_border_with rdf:resource="http://www.example.org/country4"/>
  rdf:Description>
  <rdf:Description rdf:about="http://www.example.org/country1">
    <ns1:has_border_with rdf:resource="http://www.example.org/country2"/>
    <ns1:located_in rdf:resource="http://www.example.org/part1"/>
  rdf:Description>
  <rdf:Description rdf:about="http://www.example.org/country2">
    <ns1:located_in rdf:resource="http://www.example.org/part1"/>
  rdf:Description>
  <rdf:Description rdf:about="http://www.example.org/country4">
    <ns1:located_in rdf:resource="http://www.example.org/part2"/>
  rdf:Description>
rdf:RDF>

你可能感兴趣的:(NLP,sparql,rdflib,rdf)