使用RDFLib迭代SPARQL查询

2024-09-30 05:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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编写一个for循环来访问SPARQL查询。在


Tags: node字典节点链接本体标签人体query
1条回答
网友
1楼 · 发布于 2024-09-30 05:24:03

正如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)

这样就可以将节点及其标签作为键,将所有相邻节点及其标签作为值。在

相关问题 更多 >

    热门问题