如何将 python 变量传递给 sparql 查询?

How to pass python variable to sparql query?

我会expect/hope像这样的作品:

import requests

my_variable = 'wd:Q1968435'

url = 'https://query.wikidata.org/sparql'
query = """
    SELECT ?item ?itemLabel 
        WHERE 
            {
            ?item wdt:P31 "+my_variable+".
            SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
            }
    """
r = requests.get(url, params= {'format': 'json', 'query': query})
data = r.json()

但这不起作用。有没有简单的解决办法?

提前致谢!

this answer为例,我修改了你连接多行字符串的代码如下:

import requests

my_variable = 'wd:Q1968435'

url = 'https://query.wikidata.org/sparql'
query = (
    'SELECT ?item ?itemLabel ',
     '   WHERE ',
     '       {',
     '       ?item wdt:P31 '+my_variable+'.', 
     '       SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }'
     '       }'
)

# make request: 
r = requests.get(url, params= {'format': 'json', 'query': "".join(query)})
data = r.json()
print("".join(query)) # Here I'm printing the string concatenated as single line.

# Print the result of the request.
print(data)

上一个字符串连接的结果是:

SELECT ?item ?itemLabel    WHERE        {       ?item wdt:P31 wd:Q1968435.       SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }