我拥有的:需要使用RDFlib转换为RDF的20k个字典(三元组)的列表
目标:对于每个三元组,我需要一个新的rdf图()。但是,当我循环遍历所有三元组时,方法.add()会将每个三元组累加到同一个图中
问题:如何在每个循环中创建一个新的图形,以便图形不会在每个循环中累积数据?也许有一种方法可以在每个循环中删除图形
在实际代码中,我将每个rdf转换的三元组发布到一个服务中,这需要一个接一个地完成,因为它有大量的数据(20k三元组)。对于每一个三元组,它都是它自己的出版物,所以我不能将它们全部放在同一个图表中
我的示例代码(简化):
import rdflib
from rdflib import Graph, FOAF, Literal, Namespace
list_dicts_triples = [{'subject': 'she', 'predicate': 'went', 'object': 'there'},
{'subject': 'I', 'predicate': 'like', 'object': 'ice-cream'}]
graph = Graph()
EX = Namespace('http://example.org/')
rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
graph.bind('ex', EX)
subject_rdf = rdf["subject"]
object_rdf = rdf["object"]
predicate_rdf = rdf['predicate']
for triple in list_dicts_triples:
graph.add((subject_rdf, EX.TYPE, FOAF.Person)) #subject
graph.add((predicate_rdf, rdflib.URIRef('http://example_predicates.com'), Literal(triple['predicate']))) #predicate
graph.add((object_rdf, rdflib.URIRef('http://example_concepts.com'), Literal(triple['object']))) #object
output = graph.serialize(format='ttl').decode('u8')
print(output) #print rdf graph
当前输出:(如您所见,第一个字典的项已添加到第二个rdf图中(“there”、“God”…)
#graph 1
@prefix ex: <http://example.org/> .
@prefix ns1: <http://> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
rdf:object ns1:example_concepts.com "there" .
rdf:predicate ns1:example_predicates.com "went" .
rdf:subject ex:TYPE <http://xmlns.com/foaf/0.1/Person> .
#graph 2
@prefix ex: <http://example.org/> .
@prefix ns1: <http://> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
rdf:object ns1:example_concepts.com "ice-cream",
"there" .
rdf:predicate ns1:example_predicates.com "like",
"went" .
rdf:subject ex:TYPE <http://xmlns.com/foaf/0.1/Person> .
所需输出:(这里,每个图表示列表中每个唯一的字典/三元组
#graph 1
@prefix ex: <http://example.org/> .
@prefix ns1: <http://> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
rdf:object ns1:example_concepts.com "there" .
rdf:predicate ns1:example_predicates.com "went" .
rdf:subject ex:TYPE <http://xmlns.com/foaf/0.1/Person> .
#graph 2
@prefix ex: <http://example.org/> .
@prefix ns1: <http://> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
rdf:object ns1:example_concepts.com "ice-cream".
rdf:predicate ns1:example_predicates.com "like".
rdf:subject ex:TYPE <http://xmlns.com/foaf/0.1/Person> .
在上面的代码中,您并没有为每个三元组创建新的图形。请注意,声明位于for循环的外部。把它移到里面,它就会按照你的意愿工作
相关问题 更多 >
编程相关推荐