在 rdflib -> 海龟文件中以值为单位的嵌套三元组

Nested triples with units on value in rdflib - > turtle file

我正在制作海龟文件。我必须根据 qudt.org 关联 values/units 基于下面显示的示例数据:

data = {    "objectid_l1": "Bridge_1",
            "defid_l1": "Bridge",
            "objectid_l2": "Deck_1",
            "defid_l2": "Deck",
            "variable": "height",
            "value": "50.0",
            "unit": "M",
}

我编写了以下代码,但输出不是我想要的:

from rdflib.namespace import RDF
from rdflib import URIRef, BNode, Literal, Namespace, Graph

EX = Namespace('https://example.com/id/') 
UNIT = Namespace('http://qudt.org/2.1/vocab/unit/')
BS = Namespace('https://w3id.org/def/basicsemantics-owl#')

for i in data:
        if i['objectid_l1'] != None:
                g.add((
                    EX[i['objectid_l1']],
                    RDF.type,
                    EX[i['defid_l1']]
                ))
                g.add((
                    EX[i['objectid_l1']],
                    BS['hasPart'],
                    EX[i['objectid_l2']]
                ))
                g.add((
                    EX[i['objectid_l1']],
                    EX[i['variable']],
                    EX[i['value']]
                ))
                g.add((
                    EX[i['variable']],
                    BS['unit'],
                    UNIT[i['unit']]
                ))

输出:

ex:Bridge_1
  a ex:Bridge ;
  bs:hasPart ex:Deck_1 ;
  ex:height 50.0 .

50.0 bs:unit unit:M .

作为输出,我希望单位缩进,所需的输出如下:

ex:Bridge_1
  a ex:Bridge ;
  bs:hasPart ex:Deck_1 ;
  ex:height [
      rdf:value 50.0 ;
      bs:unit unit:M ;
    ];

你的代码中缺少一些东西来实现你想要的:

  • 您需要使用 rdflib BNode 显式创建您在预期输出中显示的空白节点,然后将其用作设置高度值和单位的三元组的主题
  • 您必须指定高度值 (50.0) 是文字值。
from rdflib.namespace import RDF, XSD, NamespaceManager
from rdflib import BNode, Literal, Namespace, Graph

EX = Namespace('https://example.com/id/') 
UNIT = Namespace('http://qudt.org/2.1/vocab/unit/')
BS = Namespace('https://w3id.org/def/basicsemantics-owl#')

g = Graph()
g.namespace_manager = NamespaceManager(Graph())
g.namespace_manager.bind('unit', UNIT)
g.namespace_manager.bind('bs', BS)
g.namespace_manager.bind('ex', EX)

i = {
    "objectid_l1": "Bridge_1",
    "defid_l1": "Bridge",
    "objectid_l2": "Deck_1",
    "defid_l2": "Deck",
    "variable": "height",
    "value": "50.0",
    "unit": "M",
}

if i['objectid_l1'] != None:
    g.add((EX[i['objectid_l1']], RDF.type, EX[i['defid_l1']]))
    g.add((EX[i['objectid_l1']], BS['hasPart'], EX[i['objectid_l2']]))

    bnode = BNode()
    g.add((bnode, RDF.value, Literal(i['value'])))
    g.add((bnode, BS['unit'], UNIT[i['unit']]))
    g.add((EX[i['objectid_l1']], EX[i['variable']], bnode))

g.serialize('test.ttl', format='ttl')

应该按预期输出:

ex:Bridge_1 a ex:Bridge ;
    bs:hasPart ex:Deck_1 ;
    ex:height [ rdf:value "50.0" ;
            bs:unit unit:M ] .