今天利用rdflib中的SPARQL搜索时,需要判断搜索结果是否为空,根据查询结果所属的类追溯到了sparqlResult类,如下所示
class SPARQLResult(Result):
def __init__(self, res):
Result.__init__(self, res["type_"])
self.vars = res.get("vars_")
self.bindings = res.get("bindings")
self.askAnswer = res.get("askAnswer")
self.graph = res.get("graph")
Python代码如下:
<span style="font-size:18px;">import rdflib
g = rdflib.Graph()
g.parse("vc-db-1.rdf")
print '--------------------------------------------------'
q = u"SELECT ?x WHERE { ?x <http://www.w3.org/2001/vcard-rdf/3.0#FN> 'John Smith' }"
qres = g.query(q)
print qres.vars
# [rdflib.term.Variable(u'givenName')]
print qres.bindings
# [{rdflib.term.Variable(u'givenName'): rdflib.term.Literal(u'Rebecca')}, {rdflib.term.Variable(u'givenName'): rdflib.term.Literal(u'John')}]
print qres.graph
# None</span>
我们可以看到,qres.bindings中含有我们需要的结果,如果值为空,则输出[],所以我们只需要令qres.bindings==[]即可判断。