以 Google RDF 格式表达句子

问题描述

我想写一个python代码来表达这样的图:

吉姆 → 正在吃 → 一个苹果

苹果→在→厨房

RDF 格式。我已经在 python 中尝试过 RDFlib,但我对如何去做感到困惑。 如果有人能帮助解决这个问题,我将不胜感激。

编辑1:

我在第一句话中为 Apple 和 Jim 定义了两个 URI 节点。所以我仍然很困惑我如何用我的谓词“正在吃”来连接两个节点并将它们添加到图 g。如果有人也可以对此进行指导,我将不胜感激。

from rdflib.namespace import FOAF,XSD

# create a Graph
g = Graph()

# Create an RDF URI node to use as the subject for multiple triples
apple = URIRef("http://example.org/apple")
# Add another node
jim = URIRef("http://example.org/jim")```

解决方法

其他人就用更通用的术语定义数据模型提出了宝贵的建议。

我认为您正在寻找的是使用“添加”方法来定义主语、谓语和宾语之间的实际关系。您可以使用以下内容:


    from rdflib import Graph,Literal,RDF,URIRef
    from rdflib.namespace import FOAF,XSD
    
    # create a Graph
    g = Graph()
    
    # Create an RDF URI node to use as the subject for multiple triples
    apple = URIRef("http://example.org/apple")
    # Add another node
    jim = URIRef("http://example.org/jim")
    
    kitchen = URIRef("http://example.org/kitchen")
    
    g.add((jim,Literal("is eating"),apple))
    g.add((apple,Literal("is in"),kitchen))
    
    # print graph data in the Notation3 format
    print(g.serialize(format='n3').decode("utf-8"))

如果在您的用例中需要相应的 URIRef,您可以用适当的 URIRef 替换“正在吃”和“正在”。

您可以在 rdflib 文档中的此链接中获得有关添加三元组的更多详细信息:https://rdflib.readthedocs.io/en/stable/intro_to_creating_rdf.html#adding-triples

,

以下是使用命名空间的所需三元组的更好表述:

from rdflib import Graph,Namespace

EG = Namespace("http://example.org/")

# create a Graph,bind the namespace
g = Graph()
g.bind("eg",EG)

# Create an RDF URI nodes
apple = EG.Apple
jim = EG.Jim
kitchen = EG.Kitchen

# Create URI-based predicates
is_eating = EG.isEating
is_in = EG.isIn

g.add((jim,is_eating,apple))
g.add((apple,is_in,kitchen))

# print graph data in the Notation3 format
print(g.serialize())

# equivalent graph,using the Namespace objects directly:
g2 = Graph()
g2.bind("eg",EG)
g2.add((EG.Jim,EG.isEating,EG.Apple))
g2.add((EG.Apple,EG.isIn,EG.Kitchen))
print(g2.serialize())

请注意,除了为它们分配示例 URI 之外,这里没有真正定义任何节点或边(谓词)。如果您真的想要使用诸如 isEating 之类的关系,您将需要定义一个本体来定义该谓词,如下所示:

# ontology document snippet
...
<http://example.org/isEating>
    a owl:ObjectProperty ;
    rdfs:label "is eating" ;
    rdfs:comment "The act of consuming a resource for a living organism's energy and nutrition requirement."@en ;
    rdfs:domain foaf:Person ;
    rdfs:range ex:FoodItem ;
.
...

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...