0

I have the following:

for name in set(short_names):
    n = name.title()

    url = 'https://query.wikidata.org/sparql'
    query = """
    SELECT ?item WHERE {
      ?item rdfs:label "____________"@en

    }
    """
    r = requests.get(url, params = {'format': 'json', 'query': query})
    data = r.json()
    url = data.get('results').get('bindings')[0].get('item').get('value')
    q_id = re.search('Q.*', url).group()

    client = Client()  
    entity = client.get(q_id, load=True)
    d = entity.description
    desc.append(d)

Essentially what I am trying to do is insert the 'n' variable into _______ on every iteration of the loop.

formicaman
  • 1,317
  • 3
  • 16
  • 32

1 Answers1

0

It looks like your indentation may be off if you want your query variable to change on each iteration of the loop but you can do something like this:

for name in set(short_names):
    n = name.title()

    url = 'https://query.wikidata.org/sparql'
    query = """
    SELECT ?item WHERE {
      ?item rdfs:label "%s"@en

    }
    """ % (n)
    r = requests.get(url, params = {'format': 'json', 'query': query})
    data = r.json()
    url = data.get('results').get('bindings')[0].get('item').get('value')
    q_id = re.search('Q.*', url).group()

    client = Client()  
    entity = client.get(q_id, load=True)
    d = entity.description
    desc.append(d)

https://www.w3schools.com/python/ref_string_format.asp

%s formatting: What's the difference between %s and %d in Python string formatting?

Edited: realized that the other {} after the WHERE brake the format and f-string functions. Using the %s string formatting to avoid that potential issue.

Brock
  • 244
  • 2
  • 11
  • I get a "KeyError: '\n ?item rdfs'" error. Also: " ERROR:root:An unexpected error occurred while tokenizing input The following traceback may be corrupted or invalid The error message is: ('EOF in multi-line string', (1, 4))" – formicaman Jan 31 '20 at 19:27
  • you're right, those curly braces do break it. I'll update it again to use the %s string formatting – Brock Jan 31 '20 at 19:46