简体   繁体   English

如何在SPARQL本体查询中使用python变量?

[英]How to use python variables inside a SPARQL ontology query?

My question is probably a simple one: how can I use python variables in a SPARQL query? 我的问题可能很简单:如何在SPARQL查询中使用python变量? I'm trying to make the query to recognize something that a user typed. 我正在尝试进行查询以识别用户键入的内容。

For example, if the user types "house", the software will run the query with that entry. 例如,如果用户键入“ house”,则软件将使用该条目运行查询。 For now, I've run a test with this code (I'm using Tkinter): 现在,我已经使用以下代码运行了测试(我正在使用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)

I'm almost sure that my use of .format is wrong. 我几乎可以确定我对.format使用是错误的。 So, I ask: how to use the variables I created in this query? 因此,我问:如何使用在此查询中创建的变量? And, if I can do this with string manipulation, how is the right way to do it in this case? 而且,如果我可以通过字符串操作来做到这一点,那么在这种情况下如何正确地做到这一点呢?

I use these Python functions: 我使用以下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

So really a bit of string manipulation with " distinct?" + data + ";" 那么,是否真的使用" distinct?" + data + ";"了一些字符串操作" distinct?" + data + ";" " distinct?" + data + ";" , l = " LIMIT %s" % limit substitution, appending each string to a list and then joining the list to create the query with: complete_query = '\\n'.join(query) l = " LIMIT %s" % limit替换,将每个字符串附加到列表中,然后加入列表以使用以下命令创建查询: complete_query = '\\n'.join(query)

UPDATE: 更新:

To answer OP request more clearly: 要更清晰地回答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)

Also make sure that self.queryonto has a string representation. 还要确保self.queryonto具有string表示形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM