【问题标题】:Inserting python variable in SPARQL在 SPARQL 中插入 python 变量
【发布时间】:2022-12-03 02:09:37
【问题描述】:

我有一个字符串变量,我想在我的 SPARQL 查询中传递,但我无法让它工作。

title = 'Good Will Hunting'

[str(s) for s, in graph.query('''
    PREFIX ddis: <http://ddis.ch/atai/> 
    PREFIX wd: <http://www.wikidata.org/entity/> 
    PREFIX wdt: <http://www.wikidata.org/prop/direct/> 
    PREFIX schema: <http://schema.org/> 
    
    SELECT ?lbl WHERE {
        ?movie rdfs:label  $title@en .
        ?movie wdt:P57 ?director .
        ?director rdfs:label ?lbl .
    }
    ''')]

它不起作用,我得到一个错误。如果我在替换 $title 时手动输入名称,查询是正确的。

【问题讨论】:

    标签: python variables sparql


    【解决方案1】:

    python 中的字符串插值可以使用 %s 符号实现(对于字符串变量):

    title = 'Good Will Hunting'
    
    [str(s) for s, in graph.query('''
        PREFIX ddis: <http://ddis.ch/atai/> 
        PREFIX wd: <http://www.wikidata.org/entity/> 
        PREFIX wdt: <http://www.wikidata.org/prop/direct/> 
        PREFIX schema: <http://schema.org/> 
        
        SELECT ?lbl WHERE {
            ?movie rdfs:label "%s"@en .
            ?movie wdt:P57 ?director .
            ?director rdfs:label ?lbl .
        }
        ''' % title)]
    

    请注意,我还添加了引号 ("%s"),这是在 SPARQL 中指定字符串所必需的。

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 2016-04-30
      相关资源
      最近更新 更多