python - 如何查找了解主题或其他方式的 rdf 对象?

标签 python rdf rdflib

我正在使用 RDFLIB 在具有 ntriples 的 3 个数据集(A、B、C)之间构建图形。

目标:图表包含这些数据集 A->B、B->C 和 C->A 之间的链接,我想通过确保从 A 传出的链接指向相同的条目来检查这些链接的一致性在 A.

问题:一旦我遍历了 A->B 中的链接,我想在 B->C 中查找相应的条目(可能不止一个),对于 C->A 也是如此,是否存在一种无需遍历所有条目即可通过了解主题来查找对象的方法?

最佳答案

is there a way to look up objects by knowing the subject without iterating over all entries?

答案是肯定的。您可以使用不同的机制:(a) 有限制地迭代;或 (b) 发出 SPARQL 查询。

(a) constrain the graph and iterate

此解决方案在 Graph 对象上使用 RDFLib triples 函数。参见 this reference .

#Parse the file
g = rdflib.Graph()
g.parse("yourdata.nquads")
subject = article = rdflib.term.URIRef("http://www.someuri.org/for/your/subject")

# (subject,None,None) represents a constrain to iterate over the graph. By setting
# any of the three elements in the triple you constrain by any combination of subject,
# predicate or object. In this case we only  constrain by subject.
for triple in g.triples((subject,None,None)):
    print triple

(b) issue a SPARQL query

使用 SPARQL standard 的更标准的解决方案.

rdflib.plugin.register('sparql', rdflib.query.Processor,
                       'rdfextras.sparql.processor', 'Processor')
rdflib.plugin.register('sparql', rdflib.query.Result,
                       'rdfextras.sparql.query', 'SPARQLQueryResult')

 #Parse the file
g = rdflib.Graph()
g.parse("yourdata.nquads")

query = """
    SELECT ?pred ?obj WHERE {
         <http://www.someuri.org/for/your/subject> ?pred ?obj
    }
    """
for row in g.query(query):
    print "Predicate:%s Object:%s"%(row[0],row[1])

关于python - 如何查找了解主题或其他方式的 rdf 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5168729/

相关文章:

python - 使用 rdflib 打印出本体中每个概念的个体

python - Pyramid 返回新 session

rdf - 仅从 sparql 查询中选择第一个对象

python - 使用 RDFLib 获取 SPARQL 查询中的相交类

prolog - 使用 rdf_load 的 prolog 中的 source_sink 错误

neo4j - SPARQL中的任意路径长度查询

python - 使用 Python 中的 RDFlib 来自 RDF 的文本

python - 检查已使用 Selenium 检索到的元素是否具有特定类

python -/urlchecker/http ://www. google.com 的正则表达式是什么

java - 使用 py4j 将 Log4j 连接到 java/python 项目中的 ipython 笔记本 stderr