简体   繁体   中英

how to pattern match triples using rdflib without using SPARQL

I want to pattern match triples of an existing RDF graph. The triples() function of the RDFLib module looks like it could do the job, but I cant get it to work.

Can someone provide an example?

Consider the following graph.

@prefix ex: <http://example.com/family/> .

ex:Bob a ex:Person.
ex:Bob ex:Occupation ex:Doctor.
ex:Bob ex:Country ex:USA.
ex:Bob ex:Age ex:32.

I would like to pattern match all triples with subject ex:Bob.

I have a hunch I am using the wrong function to begin with. Can someone explain? Thanks

import rdflib
g = rdflib.Graph()
g.parse("bob.ttl", format="turtle")

bob = rdflib.URIRef("http://example.com/family/Bob")

for triple in g.triples( (bob, None, None) ):
    print(triple)

family = rdflib.Namespace('http://example.com/family/')
bob = family.Bob

for triple in g.triples( (bob, None, None) ):
    print(triple)

Note that triple patterns, as well as triples themselves, are Python tuples in RDFLib; hence one more pair of parentheses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM