使用SPARQL查询的python代码出错

时间:2017-05-20 12:57:04

标签: python dbpedia wikidata sparqlwrapper federated-queries

我正在编写一个python代码来检索DBpedia和Wikidata共有的所有actor。并获得一些额外的信息,如从wikidata收到的奖励。但它抛出一个错误。 我不知道如何纠正这个错误。这是我的python代码:

from SPARQLWrapper import SPARQLWrapper, JSON

sparql = SPARQLWrapper("https://query.wikidata.org/")
sparql.setQuery("""
PREFIX  dbp:  <http://dbpedia.org/property/>
PREFIX  movie: <http://data.linkedmdb.org/resource/movie/>
PREFIX  owl:  <http://www.w3.org/2002/07/owl#>
PREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>

SELECT DISTINCT ?Actor ?award_received
WHERE {
SERVICE <http://dbpedia.org/sparql> {
?c rdf:type <http://umbel.org/umbel/rc/Actor> . 
?c rdfs:label ?Actor.
FILTER (LANG(?Actor)="en").
?c owl:sameAs ?wikidata_actor .
   FILTER (STRSTARTS(STR(?wikidata_actor), "http://www.wikidata.org"))}
?wikidata_actor wdt:P166 ?award_received.
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()

for result in results["results"]["bindings"]:
if ("Actor" in result):
    print(result["Actor"]["value"])
else:
    url = 'NONE'

if ("award_received" in result):
    print(result["award_received"]["value"])
else:
    url = 'NONE'

这是我得到的错误:

/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 
"/Users/ashwinis/PycharmProjects/semantic web/club.py"
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
packages/SPARQLWrapper/Wrapper.py:762: RuntimeWarning: unknown response 
content type, returning raw response...
warnings.warn("unknown response content type, returning raw 
response...", RuntimeWarning)
Traceback (most recent call last):
File "/Users/ashwinis/PycharmProjects/semantic web/club.py", line 27, 
in <module>
for result in results["results"]["bindings"]:
TypeError: string indices must be integers, not str

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

  1. 维基数据SPARQL端点地址是 http://www.wikidata.org/sparql,而不是http://www.wikidata.org
  2. 请勿删除此优化提示:hint:Query hint:optimizer "None"。有关Blazegraph optimezer提示如何工作的信息,请参阅documentationon
  3. 不要忘记定义前缀(包括hint:)。
  4. 您的Python代码中存在较小的缩进问题。
  5. 不要重复提问。