如何在python的sparql查询中添加列表作为参数

时间:2019-05-07 10:58:04

标签: python sparql wikidata wikidata-api sparqlwrapper

我正在如下使用SPARQLWrapper来运行我的wikidata查询。

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)

我想将单词列表"word2vec" "fasttext" "natural language processing" "deep learning" "support vector machine"作为python列表。即如下。

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

在这种情况下,如何将mylist作为参数插入到上面已经提到的现有wikidata查询中。

我尝试如下使用f字符串。但是,它对我不起作用。

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

很高兴在需要时提供更多详细信息。

0 个答案:

没有答案