我在 rdflib 导入的帮助下使用 Python 将 rdf 格式的知识图转换为命名图格式。我还想添加一个三元组,其中指定的图声称是由主图中的源表示的,这是主图中的一个节点。我想将主图序列化为 trigf 文件,trig 文件应显示命名图及其三元组、主图的三元组以及使用命名图来显示其由来源声明的三元组。第一个问题是输出不显示文件内的命名图,第二个问题是方括号出现在图的 URIRef 周围。后者是一个问题,因为 GraphDB 无法解析这个 trig 文件。 这是我用来解决这个问题的示例代码:
from rdflib import Graph, Literal, Namespace, RDF, URIRef
# Create an RDF graph and add some data to it
rdf_graph = Graph()
# Define a namespace for your data (optional but recommended)
my_ns = Namespace("http://example.com/")
# Add some triples to the graph
rdf_graph.add((my_ns.Alice, RDF.type, my_ns.Person))
rdf_graph.add((my_ns.Alice, my_ns.hasAge, Literal(30)))
rdf_graph.add((my_ns.Bob, RDF.type, my_ns.Person))
rdf_graph.add((my_ns.Bob, my_ns.hasAge, Literal(25)))
# Create another named graph
named_graph_uri = URIRef("http://example.com/graphs/graph1")
named_graph = Graph(identifier=named_graph_uri)
# Add triples to the named graph
named_graph.add((my_ns.Alice, my_ns.likes, my_ns.Bob))
named_graph.add((my_ns.Bob, my_ns.likes, my_ns.Alice))
# Add the knowledge and the source of the knowledge to main graph
rdf_graph.add((named_graph, my_ns.saidBy, my_ns.Alice))
# Serialize main graph with the named graph within the main graph
print(rdf_graph.serialize(destination='test_file.trig' format='trig'))
这是我得到的结果:
默认RDF图:
@prefix ns1: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ns1:Bob a ns1:Person ;
ns1:hasAge 25 .
[<http://example.com/graphs/graph1>] ns1:saidBy ns1:Alice .
ns1:Alice a ns1:Person ;
ns1:hasAge 30 .
这是我期望的结果:
默认RDF图:
@prefix ns1: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ns1:Bob a ns1:Person ;
ns1:hasAge 25 .
ns1:graph1 ns1:saidBy ns1:Alice .
ns1:Alice a ns1:Person ;
ns1:hasAge 30 .
对于大多数意图和目的而言,URI 是不透明且精确的。在代码中,您需要添加另一个命名空间以在输出中获取所需的 CURIE,或者更改图形 URI 以匹配您当前拥有的命名空间。因此,要么删除图形 URI 路径中的“图形”:
named_graph_uri = URIRef("http://example.com/graph1")
或者为您的图表添加新的命名空间并相应地更改代码
from rdflib import Graph, Literal, Namespace, RDF, URIRef
# Create an RDF graph and add some data to it
rdf_graph = Graph()
# Define a namespace for your data (optional but recommended)
my_ns = Namespace("http://example.com/")
graphs_ns = Namespace("http://example.com/graphs/")
# Add some triples to the graph
rdf_graph.add((my_ns.Alice, RDF.type, my_ns.Person))
rdf_graph.add((my_ns.Alice, my_ns.hasAge, Literal(30)))
rdf_graph.add((my_ns.Bob, RDF.type, my_ns.Person))
rdf_graph.add((my_ns.Bob, my_ns.hasAge, Literal(25)))
# Create another named graph
named_graph_uri = graphs_ns.graph1
named_graph = Graph(identifier=named_graph_uri)
# Add triples to the named graph
named_graph.add((my_ns.Alice, my_ns.likes, my_ns.Bob))
named_graph.add((my_ns.Bob, my_ns.likes, my_ns.Alice))
# Add the knowledge and the source of the knowledge to main graph
rdf_graph.add((graphs_ns.graph1, my_ns.saidBy, my_ns.Alice))
# Serialize main graph with the named graph within the main graph
print(rdf_graph.serialize(destination='test_file.trig' format='trig'))