[英]Iterating over a SPARQL query with RDFLib
我有一个SPARQL查询,它检索链接到人体解剖学本体中的类的所有节点:
queryloop=graph.query("""SELECT ?node ?othernodes ?othernodesLabel WHERE {
?node rdf:type owl:Class .
?node ?y ?othernodes .
?othernodes rdfs:label ?othernodesLabel
}
LIMIT 100""")
现在,我需要遍历结果并将标签分组在python字典中,以便键包含类的标签( ?node
),并且值包含相邻节点的标签,以便对于本体有一个字典键(每个键的值和相邻类的值一样多)。 我不知道变量绑定在rdflib中是如何工作的,所以我不知道如何在python中编写可以访问SPARQL查询的for循环。
正如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)
这样,您可以将节点及其标签作为键,并将所有相邻节点及其标签作为值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.