我想将Python变量(由用户输入填充)传递给Python字符串

时间:2019-02-23 09:59:14

标签: python sparqlwrapper

这是下面的代码,我想发送python变量值来代替dbpedia:Imran_Khan。请为我提供此查询的适当解决方案 代码:

 from SPARQLWrapper import SPARQLWrapper, JSON
inputvar=input("enter name:")
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("""
PREFIX dbpedia: <http://dbpedia.org/resource/>
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://dbpedia.org/property/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdfs:   <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dct:    <http://purl.org/dc/terms/>

SELECT DISTINCT ?name  ?birthDate  ?abs ?c ?des  ?r ?bn  ?pro WHERE { 
  dbpedia:Imran_Khan # **(here I want to pass the variable in which user input is stored)** 
                     dbo:birthDate ?birthDate ;
                     dbo:abstract ?abs 
                    FILTER (lang(?abs) = 'en')

}
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
    print(result["abs"]["value"])
    print(result["birthDate"]["value"])

1 个答案:

答案 0 :(得分:0)

您应该使用此代码,我相信它可以解决您的问题,并且易于理解。

from SPARQLWrapper import SPARQLWrapper, JSON, XML, N3, RDF
print('Enter your name:')
x = input()
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("\n"
                    "    PREFIX dbpedia: <http://dbpedia.org/resource/>"
                    " PREFIX dbo: <http://dbpedia.org/ontology/>"
                    "PREFIX dbp: <http://dbpedia.org/property/>\n"
                    "PREFIX foaf: <http://xmlns.com/foaf/0.1/>\n"
                    "PREFIX rdfs:   <http://www.w3.org/2000/01/rdf-schema#>\n"
                    "PREFIX dct:    <http://purl.org/dc/terms/>\n"
                    "SELECT DISTINCT ?name  ?birthDate   WHERE {\n"
                   "dbpedia:"+x+" foaf:name ?name\n"
                    "}\n"
                    "                   ")
print('\n\n*** JSON Example')
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
    a = result["name"]["value"]
print(a)