在 rdflib 中询问 SPARQL 查询

use*_*375 2 python sparql rdflib

我正在尝试学习 SPARQL,并使用 python 的 rdflib 进行训练。我已经做了几次尝试,但任何 ASK 查询似乎总是给我返回 True 结果。例如,我尝试了以下方法:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import rdflib
mygraph=rdflib.Graph();
mygraph.parse('try.ttl',format='n3');
results=mygraph.query("""
ASK {?p1 a <http://false.com>}
 """)
print bool(results)
Run Code Online (Sandbox Code Playgroud)

即使“try.ttl”中没有 false.com 类型的主题,结果也是 true。谁能解释一下为什么?预先感谢您的帮助!

更新:阅读 rdflib 手册,我发现结果是列表类型,并且(在我的例子中)应该包含一个带有询问查询返回值的布尔值。我尝试了以下操作: for x in results: print x 我得到“无”。我猜我没有以正确的方式使用查询方法。

Jos*_*lor 5

文档实际上并没有说它是列表类型,但是您可以对其进行迭代,或者可以将其转换为布尔值:

如果类型是“ASK”,迭代将产生一个布尔值(或者 bool(result) 将返回相同的布尔值)

这意味着print bool(results),正如您所做的那样,应该可以工作。事实上,你的代码确实对我有用:

$ touch try.ttl
$ cat try.ttl # it's empty
Run Code Online (Sandbox Code Playgroud)
$ cat test.py # same code
#!/usr/bin/python
# -*- coding: utf-8 -*-
import rdflib
mygraph=rdflib.Graph();
mygraph.parse('try.ttl',format='n3');
results=mygraph.query("""
ASK {?p1 a <http://false.com>}
 """)
print bool(results)
Run Code Online (Sandbox Code Playgroud)
$ ./test.py # the data is empty, so there's no match
False
Run Code Online (Sandbox Code Playgroud)

如果我们向文件中添加一些数据以使查询返回 true,我们将得到 true:

$ cat > try.ttl 
<http://example.org> a <http://false.com> .
Run Code Online (Sandbox Code Playgroud)
$ cat try.ttl 
<http://example.org> a <http://false.com> .
Run Code Online (Sandbox Code Playgroud)
$ ./test.py 
True
Run Code Online (Sandbox Code Playgroud)

也许您正在使用旧版本的库?或者是新版本引入了错误?我正在使用4.0.1:

$ python
Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg_resources
>>> pkg_resources.get_distribution("rdflib").version
'4.0.1'
Run Code Online (Sandbox Code Playgroud)