【发布时间】:2021-12-15 23:53:20
【问题描述】:
我在使用 python 代码格式化 SPARQL 查询时遇到问题。显示的错误是:
'SELECT Distinct ?article ?item ?itemLabel ?itemDescription (GROUP_CONCAT(DISTINCT(?entity_type); separator = ", ") AS ?entity_type_list) ?main_category ?wikipediaLabel (GROUP_CONCAT(DISTINCT(?altLabel); separator = ", ") AS ?altLabel_list) WHERE'
^
SyntaxError: f-string: single '}' is not allowed
我不知道我错过了什么,有人可以帮忙吗?
def search_wikidata_label(label,lang='ar'):
sparql_query = (
'SELECT Distinct ?article ?item ?itemLabel ?itemDescription (GROUP_CONCAT(DISTINCT(?entity_type); separator = ", ") AS ?entity_type_list) ?main_category ?wikipediaLabel (GROUP_CONCAT(DISTINCT(?altLabel); separator = ", ") AS ?altLabel_list) WHERE'
'{SERVICE wikibase:mwapi'
'{ bd:serviceParam wikibase:api "EntitySearch". bd:serviceParam wikibase:endpoint "www.wikidata.org".'
f'bd:serviceParam mwapi:search "{label}".'
f'bd:serviceParam mwapi:language "{lang}" .'
'?item wikibase:apiOutputItem mwapi:item .'
'?num wikibase:apiOrdinal true .}'
'?item wdt:P31 ?entity_type .'
'MINUS { ?item wdt:P31 wd:Q4167410}'
'OPTIONAL{ ?item wdt:P910 ?main_category}'
'OPTIONAL { ?item skos:altLabel ?altLabel .'
f'FILTER (lang(?altLabel) = "{lang}") }'
'OPTIONAL{ ?article schema:about ?item;schema:isPartOf <https://ar.wikipedia.org/>;schema:name ?wikipediaLabel}'
'OPTIONAL{ ?article schema:about ?item;schema:isPartOf <https://ar.wikipedia.org/>;schema:name ?wikipediaLabel}'
'SERVICE wikibase:label {'
f'bd:serviceParam wikibase:language "{lang}" .}'
'}'
'GROUP BY ?article ?item ?itemLabel ?itemDescription ?main_category ?wikipediaLabel'
)
#to query another endpoint, change the URL for the service and the query
sparql_service_url = "https://query.wikidata.org/sparql"
result_table = query_wikidata(sparql_query, sparql_service_url)
return result_table
【问题讨论】:
-
f’bd:service…是一个 f 字符串 - 是 } 的两倍。为什么不使用三引号字符串,然后可以在字符串中包含多行。 -
阅读 f-string 的文档docs.python.org/3/reference/lexical_analysis.html#f-strings
-
我尝试了多种方法,包括三引号字符串,但它不起作用
-
@balmy 你的意思是 {lang} 和 {label},还是所有的 {
-
文档说将 {{ 或 }} 加倍以表示一个文字 { 或 },即不将它们解释为与字符串格式相关。当然,您要包围变量名称的名称保留为 { 或 }。