rdflib SPARQL查询(涉及子类)表现异常 [英] rdflib SPARQL queries (involving subclasses) not behaving as expected

查看:246
本文介绍了rdflib SPARQL查询(涉及子类)表现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始自学RDF和Python rdflib库.但是我遇到了以下代码的问题.我希望查询返回的是个人的 mark nat ,而教授是 natalie .我看不到哪里出了问题. (顺便说一句,我知道教授应该是一个头衔,而不是一个人,但我只是在修补自动取款机.)任何帮助,我们都感激不尽.谢谢.

I have just started to self-learn RDF and the Python rdflib library. But I have hit an issue with the following code. I expected the queries to return mark and nat as Persons and only natalie as a Professor. I can't see where I've gone wrong. (BTW, I know Professor should be a title rather than a kind of Person, but I'm just tinkering ATM.) Any help appreciated. Thanks.

rdflib 4,Python 2.7

rdflib 4, Python 2.7

>>> from rdflib import Graph, BNode, URIRef, Literal
INFO:rdflib:RDFLib Version: 4.2.
>>> from rdflib.namespace import RDF, RDFS, FOAF
>>> G = Graph()
>>> mark = BNode()
>>> nat = BNode()
>>> G.add((mark, RDF.type, FOAF.Person))
>>> G.add((mark, FOAF.firstName, Literal('mark')))
>>> G.add((URIRef('Professor'), RDF.type, RDFS.Class))
>>> G.add((URIRef('Professor'), RDFS.subClassOf, FOAF.Person))
>>> G.add((nat, RDF.type, URIRef('Professor')))
>>> G.add((nat, FOAF.firstName, Literal('natalie')))
>>> qres = G.query(
        """SELECT DISTINCT ?aname
           WHERE {
              ?a rdf:type foaf:Person .
              ?a foaf:firstName ?aname .
           }""", initNs = {"rdf": RDF,"foaf": FOAF})
>>> for row in qres:
    print "%s is a person" % row


mark is a person
>>> qres = G.query(
        """SELECT DISTINCT ?aname
           WHERE {
              ?a rdf:type ?prof .
              ?a foaf:firstName ?aname .
           }""", initNs = {"rdf": RDF,"foaf": FOAF, "prof": URIRef('Professor')})
>>> for row in qres:
    print "%s is a Prof" % row


natalie is a Prof
mark is a Prof
>>> 

推荐答案

您的查询将带回所有类型,因为?prof变量未绑定到值.

Your query is bringing back all types because the ?prof variable isn't bound to a value.

我认为您要使用的是 initBindings kwarg将教授"的URI传递给您的查询.因此,将查询更改为以下内容将仅检索natalie.

I think you want to use is the initBindings kwarg to pass in the URI for 'Professor' to your query. So changing your query to below retrieves just natalie.

qres = G.query( """SELECT DISTINCT ?aname WHERE { ?a rdf:type ?prof . ?a foaf:firstName ?aname . }""", initNs ={"rdf": RDF,"foaf": FOAF}, initBindings={"prof": URIRef('Professor')})

qres = G.query( """SELECT DISTINCT ?aname WHERE { ?a rdf:type ?prof . ?a foaf:firstName ?aname . }""", initNs ={"rdf": RDF,"foaf": FOAF}, initBindings={"prof": URIRef('Professor')})

这篇关于rdflib SPARQL查询(涉及子类)表现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆