我的问题可能很简单:如何在SPARQL查询中使用python变量?我正在尝试进行查询以识别用户键入的内容。
例如,如果用户键入“ house”,则软件将使用该条目运行查询。现在,我已经使用此代码运行了一个测试(我正在使用Tkinter):
self.queryonto = Entry(self.frame1)
self.queryonto.pack(side=LEFT)
self.btnquery = Button(self.frame1, text='Query ontology')
self.btnquery['command'] = self.makequery
self.btnquery.pack(side=LEFT)
def makequery(self):
self.ontology = World()
self.onto = self.ontology.get_ontology('file://file.owl').load()
self.baseiri = self.onto.base_iri
self.graph = self.ontology.as_rdflib_graph()
self.request = """PREFIX ont: <{}>
SELECT ?class
WHERE {
ont:{} a ?class .
}""".format(self.baseiri, self.queryonto)
self.results = list(self.graph.query(self.request))
print(self.results)
我几乎可以确定我对.format
的使用是错误的。因此,我问:如何使用在此查询中创建的变量?而且,如果我可以通过字符串操作来做到这一点,在这种情况下如何正确地做到这一点?
答案 0 :(得分:0)
我使用以下Python函数:
def createConcat(self, data, separator = ";;;"):
""" Creates concat string. """
return "(group_concat(distinct ?"+data+";separator='"+separator+"') as ?"+data+"_s)"
def createSparqlQuery(self, data, separator = ";;;", key = "root", offset = 100):
"""Generates SPARQL query from input file."""
query = []
orderby = []
select = "SELECT DISTINCT"
#from_each_subpage
for prop in data['select']:
if prop.endswith("_s"):
select +=" "+ self.createConcat(prop.split("_")[0])
else:
v = "?"+ prop.replace('_X','')
select += " "+ v
orderby.append(v)
where = " WHERE { "
closing = 1
query.append(select)
query.append(where)
try:
service = "SERVICE "+data['service'] + " {"
query.append(service)
closing += 1
except:
pass
query.append('\n'.join(data[key]))
while closing > 0:
query.append('}')
closing -= 1
o = " ORDER BY " + ' '.join(orderby)
query.append(o)
try:
limit = data['limit']
l = " LIMIT %s" % limit
query.append(l)
except:
pass
complete_query = '\n'.join(query)
print complete_query
return complete_query
实际上是使用" distinct?" + data + ";"
,l = " LIMIT %s" % limit
替换进行了一些字符串操作,将每个字符串附加到列表中,然后加入列表以使用以下内容创建查询:complete_query = '\n'.join(query)
更新:
要更清晰地回答OP请求:
query_parts = []
baseiri = "PREFIX ont: <%s>" % self.baseiri
select_where = "SELECT ?class WHERE {"
queryonto = "ont: %s a ?class ." % self.queryonto
closing = "}"
query_parts.append(baseiri)
query_parts.append(select_where)
query_parts.append(queryonto)
query_parts.append(closing)
self.request = "\n".join(query_parts)
还要确保self.queryonto
具有string
表示形式。