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

如何使用Wikidata第三方库直接获取指定实体的RDF三元组

基于wikidata库获取实体全量RDF三元组的实现方法

获取出边三元组(实体作为主语)

你已经通过client.get()加载了实体实例后,直接遍历实例的键值对即可提取所有出边三元组,示例代码如下:

from wikidata.client import Client

client = Client()
# 加载IU对应的实体Q20145
entity = client.get('Q20145', load=True)

out_triples = []
for pred, value in entity.items():
    # 三元组格式:(主语id, 谓语id, 宾语值/宾语id)
    triple = (
        entity.id,
        pred.id,
        value.id if isinstance(value, type(entity)) else str(value)
    )
    out_triples.append(triple)

# 查看前3条出边
print(out_triples[:3])

说明:如果属性值是Wikidata实体就取其id,要是是时间、数值、字符串等字面量就直接保留原值。

获取入边三元组(实体作为宾语)

wikidata第三方库本身没有封装入边查询的原生接口,要实现该需求可以配合SPARQL查询后解析结果,示例代码如下:

import requests

entity_id = 'Q20145'
in_triples = []

# 构造SPARQL查询语句,查询所有以当前实体为宾语的三元组
query = f"""
SELECT ?subj ?pred WHERE {{
  ?subj ?pred wd:{entity_id} .
}}
"""
# 发起查询请求
resp = requests.get(
    "https://query.wikidata.org/sparql",
    params={"query": query, "format": "json"}
)
# 解析返回结果
for bind in resp.json()["results"]["bindings"]:
    subj_id = bind["subj"]["value"].split("/")[-1]
    pred_id = bind["pred"]["value"].split("/")[-1]
    in_triples.append((subj_id, pred_id, entity_id))

# 查看前3条入边
print(in_triples[:3])

注意:Wikidata公共查询接口有访问频率限制,短时间大量查询需添加请求间隔避免被限制访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:15:01