-1

这是我下面的代码,我想发送 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"])
4

1 回答 1

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)
于 2019-02-25T10:33:27.417 回答