How to add special categories in sparqlwrapper in python

你离开我真会死。 提交于 2019-12-13 04:28:16

问题


I am using the following sparql query using sparqlwrapper as follows.

from SPARQLWrapper import SPARQLWrapper, JSON
sparql = SPARQLWrapper("http://live.dbpedia.org/sparql")
sparql.setReturnFormat(JSON)
my_category = 'dbc:Meteorological_concepts'
sparql.setQuery(f" ASK {{ {my_category}  skos:broader{{1,3}} dbc:Medicine }} ")
results = sparql.query().convert()
print(results['boolean'])

As mentioned above it works fine with categories that do not have brackets (e.g., dbc:Meteorological_concepts). However, when I enter a category with brackets (i.e my_category = dbc:Elasticity_(physics)) I get the following error.

b"Virtuoso 37000 Error SP030: SPARQL compiler, line 4: syntax error at 'physics' before ')'\n\nSPARQL query:\ndefine sql:big-data-const 0 \n#output-format:application/sparql-results+json\n\n    ASK { dbc:Elasticity_(physics) skos:broader{1,3} dbc:Medicine }\n"
CRITICAL: Exiting due to uncaught exception <class 'SPARQLWrapper.SPARQLExceptions.QueryBadFormed'>

Is there a way to resolve this issue.

I am happy to provide more details if needed.


回答1:


I am rewriting what @StanislavKralin mentioned in the above comment. I always try to use full URL in the SPARQL code, particularly when there is special character in SPARQL query.

from SPARQLWrapper import SPARQLWrapper, JSON
sparql = SPARQLWrapper("http://live.dbpedia.org/sparql")
sparql.setReturnFormat(JSON)
my_category = '<http://dbpedia.org/resource/Category:Elasticity_(physics)>'
sparql.setQuery(f" ASK {{ {my_category}  skos:broader{{1,3}} dbc:Medicine }} ")
results = sparql.query().convert()
print(results['boolean'])


来源:https://stackoverflow.com/questions/55206966/how-to-add-special-categories-in-sparqlwrapper-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!