rdflib triples 匹配始终为空的问题

写代码的时候遇到了一个问题,花了好长时间解决,记录一下,避免再出问题
完整代码如下所示:

# 导入用于处理文件的标准库
import os
from rdflib import Graph, URIRef
# 指定要创建的TTL文件的名称
filename = "example.ttl"

# 创建文件并打开
with open(filename, 'w') as file:
    # 写入第一个命名空间声明
    file.write("@prefix ex: <http://example.com/> .\n")
    # 写入第二个命名空间声明
    file.write("@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n")
    file.write("\n")  # 添加一个空行以分隔命名空间声明和资源描述

    # 使用命名空间前缀写入资源描述
    file.write("ex:resource1  a  ex:Resource ;\n")
    file.write("         ex:property  \"value1\" .\n")
    file.write("\n")  # 添加一个空行以分隔不同的资源描述

    file.write("ex:resource2  a  ex:Resource ;\n")
    file.write("         ex:property  \"value2\" .\n")
    file.write("\n")  # 添加一个空行以分隔不同的资源描述
    # 也可以使用第二个命名空间来描述资源
    file.write("foaf:person  a  foaf:Person ;\n")
    file.write("         foaf:name  \"John Doe\" .\n")

# 打印文件已创建的消息
print(f"TTL file '{filename}' has been created.")

# 指定TTL文件的名称
filename = "example.ttl"

# 创建一个RDF图对象
g = Graph()

# 读取文件并将其内容加载到RDF图对象中
g.parse(filename, format='turtle')

# 现在可以查询图对象了。例如,查询所有资源及其属性:
for s, p, o in g:
    print(f"Subject: {s}, Predicate: {p}, Object: {o}")

# 打印图中所有的主语,看看是否有你期望的资源URI
print("All subjects in the graph:")
for s in g.subjects():
    print(s)
resource_uri="http://example.com/resource1"

# 使用startswith方法检查URI的开头部分
if any(s.startswith(resource_uri) for s in g.subjects()):
    print(f"{resource_uri} exists in the graph.")
# 检查资源URI是否在图中
if resource_uri in g.subjects():
    print(f"{resource_uri} exists in the graph.")

# 查询与资源URI相关的三元组
print("Triples related to resource_uri:")
for s, p, o in g.triples((None, None, None)):
    if s.startswith(resource_uri):
        print(f"Resource: {s}, Property: {p}, Value: {o}")
print("Triples related to resource_uri:")
for s, p, o in g.triples((resource_uri, None, None)):
    print(f"Resource: {s}, Property: {p}, Value: {o}")

# 关闭图对象(虽然在Python脚本结束时会自动关闭,但显式关闭是一个好习惯)
g.close()

在这里发现资源存在,存储正确,但是相应的triples匹配始终输出为空,花了好久时间排查,这里是需要加入URIRef(),即将

for s, p, o in g.triples((resource_uri, None, None)):
    print(f"Resource: {s}, Property: {p}, Value: {o}")

改为

for s, p, o in g.triples((URIRef(resource_uri), None, None)):
    print(f"Resource: {s}, Property: {p}, Value: {o}")

或者可以使用

from rdflib import Graph, URIRef, Namespace
yaga = Namespace("http://example.com/resource1")
resource_uri = yaga.resource1
print("Triples related to resource_uri:")
for s, p, o in g.triples((resource_uri, None, None)):
    print(f"Resource: {s}, Property: {p}, Value: {o}")
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值