2

我正在尝试学习 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)

结果为真,即使 'try.ttl' 中没有 false.com 类型的主题。谁能解释我为什么?预先感谢您的帮助!

更新:阅读 rdflib 手册,我发现 results 的类型是 list 并且(在我的情况下)应该包含一个带有来自 ask 查询的返回值的布尔值。我尝试了以下方法: for x in results: print x 我得到了“无”。我猜我没有以正确的方式使用查询方法。

4

1 回答 1

5

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

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

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

$ touch try.ttl
$ cat try.ttl # it's empty
$ 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)
$ ./test.py # the data is empty, so there's no match
False

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

$ cat > try.ttl 
<http://example.org> a <http://false.com> .
$ cat try.ttl 
<http://example.org> a <http://false.com> .
$ ./test.py 
True

也许您使用的是旧版本的库?还是引入了较新的版本和错误?我正在使用 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'
于 2014-07-15T22:35:48.873 回答