简体   繁体   中英

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:

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). 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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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