1

I am using SPARQLWrapper as follows to run my Wikidata query.

from SPARQLWrapper import SPARQLWrapper, JSON
import pandas as pd

sparql = SPARQLWrapper("https://query.wikidata.org/sparql")

sparql.setQuery("""
    SELECT DISTINCT ?item {
    VALUES ?searchTerm { "word2vec" "fasttext" "natural language processing" "deep learning" "support vector machine" }
    SERVICE wikibase:mwapi {
        bd:serviceParam wikibase:api "EntitySearch".
        bd:serviceParam wikibase:endpoint "www.wikidata.org".
        bd:serviceParam wikibase:limit 3 .
        bd:serviceParam mwapi:search ?searchTerm.
        bd:serviceParam mwapi:language "en".
        ?item wikibase:apiOutputItem mwapi:item.
        ?num wikibase:apiOrdinal true.
    }
    ?item (wdt:P279|wdt:P31) ?type
    }
    ORDER BY ?searchTerm ?num                    
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
results_df = pd.io.json.json_normalize(results['results']['bindings'])
print(results_df)

I would like to give the wordlist "word2vec" "fasttext" "natural language processing" "deep learning" "support vector machine" as a python list. i.e. as follows.

mylist = ["word2vec", "fasttext", "natural language processing", "deep learning", "support vector machine"]

In that case, how can I insert mylist as a parameter to my existing wikidata query that I have mentioned above.

I tried to use f-strings as follows. However, it did not work for me.

sparql.setQuery(f"
        SELECT DISTINCT ?item {
        VALUES ?searchTerm { {mylist} }
        SERVICE wikibase:mwapi {
            bd:serviceParam wikibase:api "EntitySearch".
            bd:serviceParam wikibase:endpoint "www.wikidata.org".
            bd:serviceParam wikibase:limit 3 .
            bd:serviceParam mwapi:search ?searchTerm.
            bd:serviceParam mwapi:language "en".
            ?item wikibase:apiOutputItem mwapi:item.
            ?num wikibase:apiOrdinal true.
        }
        ?item (wdt:P279|wdt:P31) ?type
        }
        ORDER BY ?searchTerm ?num                    
    ")

I am happy to provide more details if needed.

logi-kal
  • 7,107
  • 6
  • 31
  • 43
EmJ
  • 4,398
  • 9
  • 44
  • 105
  • 1
    https://stackoverflow.com/questions/10112614/how-do-i-create-a-multiline-python-string-with-inline-variables/10112660 and it's clearly that you have to create a string out of the list first, otherwise you have the commas. Python string join is the way to go: https://www.programiz.com/python-programming/methods/string/join – UninformedUser May 07 '19 at 12:17
  • 2
    https://paws-public.wmflabs.org/paws-public/User:Luitzen/Concat.ipynb – Stanislav Kralin May 07 '19 at 12:35
  • @AKSW Thanks a lot. It was very helpful :) – EmJ May 07 '19 at 12:51
  • @StanislavKralin Thanks a lot. It worked :) – EmJ May 07 '19 at 12:52

0 Answers0