我有以下代码:
name = [str(s) for s, in graph.query('''
SELECT ?lbl
WHERE {
<http://www.wikidata.org/entity/Q59692464> <http://www.wikidata.org/prop/direct/P1657> ?obj .
?obj rdfs:label ?lbl .
}
''')]
我想传递两个值<http://www.wikidata.org/entity/Q59692464>
和<http://www.wikidata.org/prop/direct/P1657>
作为变量?mov
和?rel
.
我尝试使用 %s 但出现错误:
name = [str(s) for s, in graph.query('''
SELECT ?lbl
WHERE {
<'%s'> <http://www.wikidata.org/prop/direct/P1657> ?obj .
?obj rdfs:label ?lbl .
}
'''%mov)]
TypeError: unsupported operand type(s) for %: 'SPARQLResult' and 'str'
我想要的是这样的:
name = [str(s) for s, in graph.query('''
SELECT ?lbl
WHERE {
?mov ?rel ?obj .
?obj rdfs:label ?lbl .
}
''')]
非常感谢您的帮助!
最佳答案
假设您使用rdflib
,您可以执行以下操作:
mov = rdflib.URIRef("http://www.wikidata.org/entity/Q59692464")
rel = rdflib.URIRef("http://www.wikidata.org/prop/direct/P1657")
name = [str(s) for s, in graph.query('''
SELECT ?lbl
WHERE {
?mov ?rel ?obj .
?obj rdfs:label ?lbl .
}
''', initBindings={'mov': mov, 'rel': rel})]
关于python - 如何向 SPARQL 查询添加外部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74738408/