简体   繁体   English

使用RDFLib遍历SPARQL查询

[英]Iterating over a SPARQL query with RDFLib

I have a SPARQL query that retrieves all the nodes linked to the classes in an ontology of the human anatomy: 我有一个SPARQL查询,它检索链接到人体解剖学本体中的类的所有节点:

queryloop=graph.query("""SELECT ?node ?othernodes ?othernodesLabel WHERE { 
?node rdf:type owl:Class .
?node ?y ?othernodes .
?othernodes rdfs:label ?othernodesLabel
} 
LIMIT 100""")

I now need to iterate over the results and group the labels in a python dictionary, so that the key contains the label of the class ( ?node ), and the value contains the labels of the adjoining nodes, so that for every class in the ontology there is a dictionary key (and for each key there are as many values as adjoining classes). 现在,我需要遍历结果并将标签分组在python字典中,以便键包含类的标签( ?node ),并且值包含相邻节点的标签,以便对于本体有一个字典键(每个键的值和相邻类的值一样多)。 I don't know how variable bindings work in rdflib so I don't know how to write a for-loop in python that would have access to the SPARQL query. 我不知道变量绑定在rdflib中是如何工作的,所以我不知道如何在python中编写可以访问SPARQL查询的for循环。

As AKSW pointed out, the easiest way to do this would be to include whatever elements you want to transfer to the dictionary in the SPARQL query, and then access them as attributes before appending them to the dictionary like so: 正如AKSW指出的那样,最简单的方法是在SPARQL查询中包括要转移到字典中的任何元素,然后将它们作为属性访问,然后将它们附加到字典中,如下所示:

queryloop=graph.query("""SELECT ?node ?nodelabel ?othernodes ?othernodesLabel     WHERE { 
?node rdf:type owl:Class .
?node ?y ?othernodes .
?othernodes rdfs:label ?othernodesLabel
?node rdfs:label ?nodeLabel
} 
LIMIT 100""")

dictlabels={}
for row in queryloop:
    dictlabels.update(row.node, row.nodeLabel: row.othernodes,row.othernodesLabel)

This way you have the node and its label as the key, and all the adjoining nodes and their labels as the values. 这样,您可以将节点及其标签作为键,并将所有相邻节点及其标签作为值。

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

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