python函数中SPARQL查询的用户输入



我正在python中编写一个函数,该函数调用API的SPARQL端点。我想根据用户输入修改查询(mesh:"+d+"meshv:treeNumber?treeNum.(。下面是我的函数。

def get_disease(d):
query = '''
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 owl: <http://www.w3.org/2002/07/owl#>
PREFIX meshv: <http://id.nlm.nih.gov/mesh/vocab#>
PREFIX mesh: <http://id.nlm.nih.gov/mesh/>
PREFIX mesh2022: <http://id.nlm.nih.gov/mesh/2022/>

SELECT DISTINCT ?descriptor ?label
FROM <http://id.nlm.nih.gov/mesh>
WHERE {
mesh:"+d+" meshv:treeNumber ?treeNum .
?childTreeNum meshv:parentTreeNumber+ ?treeNum .
?descriptor meshv:treeNumber ?childTreeNum .
?descriptor rdfs:label ?label .
}
ORDER BY ?label
'''
#set the url
url = 'https://id.nlm.nih.gov/mesh/sparql'
#set the header
headers = {'Content-Type': 'application/sparql-results+json'}
#set the parameters
params = {'query' : query, 'limit' : 1000, 'inference' : 'true', 'format' : 'JSON'}

#send the request
response = requests.get(url, headers = headers, params = params)
jsonResponse = response.json()['results']

get_disease('D020521')

我查看了以前的帖子,其中显示"+d+"'在这种情况下,输入项("D002521"(的串联应该有效。然而,我得到以下错误。

JSONDecodeError: [Errno Expecting value] Encountered " <STRING_LITERAL2> ""+d+" "" at line 16, column 14.
Was expecting one of:
<IRIref> ...
<PNAME_NS> ...
<PNAME_LN> ...
<VAR1> ...
<VAR2> ...
"a" ...
"distinct" ...
"multi" ...
"shortest" ...
"(" ...
"!" ...
"^" ...
: 0

非常感谢您的帮助。

感谢@UniinformedUser。脚本中的以下更改成功了!

´´def get_disease(d(:

query = '''
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 owl: <http://www.w3.org/2002/07/owl#>
PREFIX meshv: <http://id.nlm.nih.gov/mesh/vocab#>
PREFIX mesh: <http://id.nlm.nih.gov/mesh/>
PREFIX mesh2022: <http://id.nlm.nih.gov/mesh/2022/>
SELECT DISTINCT ?descriptor ?label
FROM <http://id.nlm.nih.gov/mesh>
WHERE {
#mesh:D020521 meshv:treeNumber ?treeNum .
mesh:%s meshv:treeNumber ?treeNum .
?childTreeNum meshv:parentTreeNumber+ ?treeNum .
?descriptor meshv:treeNumber ?childTreeNum .
?descriptor rdfs:label ?label .
}
ORDER BY ?label
'''%(d)
#set the url
url = 'https://id.nlm.nih.gov/mesh/sparql'
#set the header
headers = {'Content-Type': 'application/sparql-results+json'}
#set the parameters
params = {'query' : query, 'limit' : 1000, 'inference' : 'true', 'format' : 'JSON'}
#send the request
response = requests.get(url, headers = headers, params = params)
jsonResponse = response.json()['results']
print (jsonResponse)    

get_disease('020521'(´´

最新更新