简体   繁体   中英

How to pass python variable to sparql query?

I would expect/hope something like this works:

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()

But this does not work. Is there a simple solution?

Thanks in advance!

Taking as example this answer , I modified your code for concatenating your multiline string as follows:

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)

The result of the previous string concatenation is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM