You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中对外部SPARQL查询字符串进行f-string插值?

解决方案

方法1:使用字符串format()方法(推荐,安全直观)

这是最稳妥的方式,直接利用Python字符串的格式化功能匹配模板中的占位符:

在sample.py中修改代码:

from SPARQLWrapper import SPARQLWrapper
from sparqlqueries import DBP_LANGS

sparql = SPARQLWrapper("http://dbpedia.org/sparql")

QUERY_LIMIT = 5
# 对导入的查询字符串进行格式化
formatted_query = DBP_LANGS.format(QUERY_LIMIT=QUERY_LIMIT)
print(formatted_query)
sparql.setQuery(formatted_query)

方法2:动态生成f-string(需注意安全)

如果一定要用f-string语法实现,可以通过eval动态完成,但仅在完全信任模板字符串来源时使用,避免代码注入风险:

from SPARQLWrapper import SPARQLWrapper
from sparqlqueries import DBP_LANGS

sparql = SPARQLWrapper("http://dbpedia.org/sparql")

QUERY_LIMIT = 5
# 动态构造f-string并求值
formatted_query = eval(f"f'''{DBP_LANGS}'''")
print(formatted_query)
sparql.setQuery(formatted_query)

方法3:将模板封装为函数(更易维护)

修改sparqlqueries.py,把查询模板改成带参数的函数,逻辑更清晰也方便后续扩展:

# sparqlqueries.py
def get_dbp_langs_query(query_limit):
    return f"""
    PREFIX dbo: <http://dbpedia.org/ontology/>
    PREFIX sdo: <https://schema.org/>

    CONSTRUCT {{
      ?lang a sdo:Language ;
      sdo:alternateName ?iso6391Code .
    }}
    WHERE {{
      ?lang a dbo:Language ;
      dbo:iso6391Code ?iso6391Code .
      FILTER (STRLEN(?iso6391Code)=2) # to filter out non-valid values
    }}
    LIMIT {query_limit}
    """

然后在sample.py中调用:

from SPARQLWrapper import SPARQLWrapper
from sparqlqueries import get_dbp_langs_query

sparql = SPARQLWrapper("http://dbpedia.org/sparql")

QUERY_LIMIT = 5
formatted_query = get_dbp_langs_query(QUERY_LIMIT)
print(formatted_query)
sparql.setQuery(formatted_query)

内容的提问来源于stack exchange,提问作者Robert Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:31:21