当前位置: 首页>>代码示例>>Python>>正文


Python ConjunctiveGraph.objects方法代码示例

本文整理汇总了Python中rdflib.ConjunctiveGraph.objects方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.objects方法的具体用法?Python ConjunctiveGraph.objects怎么用?Python ConjunctiveGraph.objects使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rdflib.ConjunctiveGraph的用法示例。


在下文中一共展示了ConjunctiveGraph.objects方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_remove_period

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
    def test_remove_period(self):
        with open(filepath('test-patch-remove-period.json')) as f:
            patch1 = f.read()
        with self.client as client:
            res = client.patch(
                '/d/',
                data=patch1,
                content_type='application/json',
                headers={'Authorization': 'Bearer '
                         + 'NTAwNWViMTgtYmU2Yi00YWMwLWIwODQtMDQ0MzI4OWIzMzc4'})
            patch_url = urlparse(res.headers['Location']).path
            res = client.post(
                patch_url + 'merge',
                buffered=True,
                headers={'Authorization': 'Bearer '
                         + 'ZjdjNjQ1ODQtMDc1MC00Y2I2LThjODEtMjkzMmY1ZGFhYmI4'})
            self.assertEqual(res.status_code, http.client.NO_CONTENT)
            removed_entities = database.get_removed_entity_keys()
            self.assertEqual(removed_entities, set(['p0trgkvwbjd']))
            res = client.get('/trgkvwbjd',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.GONE)
            res = client.get('/trgkvwbjd.json',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.GONE)
            res = client.get('/trgkvwbjd?version=0',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.NOT_FOUND)
            res = client.get('/trgkvwbjd.json?version=0',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.NOT_FOUND)
            res = client.get('/trgkvwbjd?version=1',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.OK)
            res = client.get('/trgkvwbjd.json?version=1',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.OK)

            res = client.get('/history.jsonld?inline-context')
            self.assertEqual(
                res.headers['Cache-Control'],
                'public, max-age=0')
            self.assertEqual(
                res.headers['X-Accel-Expires'],
                '{}'.format(cache.MEDIUM_TIME))

            g = ConjunctiveGraph()
            g.parse(format='json-ld', data=res.get_data(as_text=True))

            generated = list(g.objects(subject=HOST['h#change-2'],
                                       predicate=PROV.generated))
            self.assertEqual(len(generated), 1)
            self.assertIn(HOST['d?version=2'], generated)
开发者ID:periodo,项目名称:periodo-server,代码行数:61,代码来源:test_patch.py

示例2: get_uri_types

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
def get_uri_types(uri, lang):
    g = ConjunctiveGraph('SPARQLStore')
    g.open(get_dbpedia_endpoint(lang))

    #print uri
    #print len(list( g.triples(( URIRef(uri), URIRef('http://dbpedia.org/ontology/country'), URIRef('http://es.dbpedia.org/resource/España') )) ))

    return [ str(typ) for typ in g.objects(URIRef(uri), RDF.type) ]
开发者ID:OpenDataDayBilbao,项目名称:teseo2014,代码行数:10,代码来源:universities_dbpedia.py

示例3: get_mediator_account

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
def get_mediator_account(user_uuid):
    uri = URIRef("http://vocab.ox.ac.uk/owner/%s"%user_uuid)
    graph = Graph()
    graph.parse(ag.mediatorslist)
    for account in graph.objects(uri, namespaces['foaf']['account']):
        if account:
            return account
    return False
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:10,代码来源:rdf_helper.py

示例4: get_mediator_details

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
def get_mediator_details(userid):
    #Get mediator_details - firstname, lastname, department, email
    details = {}
    details['userid'] = userid
    details['uri'] = None
    details['name'] = None
    details['fname'] = None
    details['lname'] = None
    details['title'] = None
    details['email'] = None
    details['dept'] = []
    if userid.startswith('uuid'):
        userid = get_mediator_account(userid)
        details['userid'] = userid
        if not userid:
            return details
    if not os.path.isfile(os.path.join(ag.mediatorsdir, '%s.rdf'%userid)):
        return details
    graph = Graph()
    graph.parse(os.path.join(ag.mediatorsdir, '%s.rdf'%userid))
    t = ''
    f = ''
    l = ''
    for title in graph.objects(None, namespaces['foaf']['title']):
        if title.strip():
            t = title
            details['title'] = t
    for fname in graph.objects(None, namespaces['foaf']['firstName']):
        if fname.strip():
            f = fname
            details['fname'] = fname
    for lname in graph.objects(None, namespaces['foaf']['lastName']):
        if lname.strip():
            l = lname
            details['lname'] = lname
    details['name'] = "%s %s %s"%(t, f, l)
    details['name'] = details['name'].strip()
    if not details['name']:
        details['name'] = userid
    for email in graph.objects(None, namespaces['foaf']['mbox']):
        details['email'] = email
    for dept in graph.objects(None, namespaces['dcterms']['isPartOf']):
        details['dept'].append(dept)
    for uri in graph.subjects(namespaces['foaf']['account'], None):
        details['uri'] = uri
    return details
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:48,代码来源:rdf_helper.py

示例5: test_remove_definition

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
    def test_remove_definition(self):
        with open(filepath('test-patch-remove-definition.json')) as f:
            patch1 = f.read()
        with self.client as client:
            res = client.patch(
                '/d/',
                data=patch1,
                content_type='application/json',
                headers={'Authorization': 'Bearer '
                         + 'NTAwNWViMTgtYmU2Yi00YWMwLWIwODQtMDQ0MzI4OWIzMzc4'})
            patch_url = urlparse(res.headers['Location']).path
            res = client.post(
                patch_url + 'merge',
                headers={'Authorization': 'Bearer '
                         + 'ZjdjNjQ1ODQtMDc1MC00Y2I2LThjODEtMjkzMmY1ZGFhYmI4'})
            self.assertEqual(res.status_code, http.client.NO_CONTENT)
            removed_entities = database.get_removed_entity_keys()
            self.assertEqual(removed_entities, set(['p0trgkvwbjd']))
            res = client.get('/trgkvwbjd',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.GONE)
            res = client.get('/trgkvwbjd.json',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.GONE)
            res = client.get('/trgkvwbjd?version=0',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.NOT_FOUND)
            res = client.get('/trgkvwbjd.json?version=0',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.NOT_FOUND)
            res = client.get('/trgkvwbjd?version=1',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.OK)
            res = client.get('/trgkvwbjd.json?version=1',
                             headers={'Accept': 'application/json'},
                             follow_redirects=True)
            self.assertEqual(res.status_code, http.client.OK)

            res = client.get('/h')

            g = ConjunctiveGraph()
            g.parse(format='json-ld', data=res.get_data(as_text=True))

            invalidated = g.value(subject=PERIODO['p0h#change-2'],
                                  predicate=PROV.invalidated,
                                  any=False)
            self.assertEqual(invalidated, PERIODO['p0trgkvwbjd'])

            generated = list(g.objects(subject=PERIODO['p0h#change-2'],
                                       predicate=PROV.generated))
            self.assertEqual(len(generated), 2)
            self.assertIn(PERIODO['p0d?version=2'], generated)
            self.assertIn(PERIODO['p0trgkv?version=2'], generated)
开发者ID:weberjavi,项目名称:periodo-server,代码行数:60,代码来源:test_patch.py

示例6: get_vocab_properties

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
def get_vocab_properties(vocabprefix):
    vocab_uri = URIRef("http://vocab.ox.ac.uk/%s"%vocabprefix)
    vocabdir = os.path.join(ag.vocabulariesdir, vocabprefix)
    vocabstatusfile = os.path.join(vocabdir, "status.rdf")
    properties = {}
    properties['uri'] = vocab_uri
    if not os.path.isfile(vocabstatusfile):
        return properties
    properties['path'] = vocabdir
    properties['preferredNamespaceUri'] = None
    properties['preferredNamespacePrefix'] = None
    graph = Graph()
    graph.parse(vocabstatusfile)
    for o in graph.objects(None, namespaces['vann']['preferredNamespaceUri']):
        properties['preferredNamespaceUri'] = o
    for o in graph.objects(None, namespaces['vann']['preferredNamespacePrefix']):
        properties['preferredNamespacePrefix'] = o
    return properties
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:20,代码来源:rdf_helper.py

示例7: get_vocab_mediator

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
def get_vocab_mediator(vocabprefix):
    vocab_uri = URIRef("http://vocab.ox.ac.uk/%s"%vocabprefix)
    vocabdir = os.path.join(ag.vocabulariesdir, vocabprefix)
    vocabstatusfile = os.path.join(vocabdir, "status.rdf")
    mediators = {}
    if not os.path.isfile(vocabstatusfile):
        return mediators
    graph = Graph()
    graph.parse(vocabstatusfile)
    for o in graph.objects(None, namespaces['foaf']['account']):
        mediators[str(o)] = get_mediator_details(str(o))
    return mediators
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:14,代码来源:rdf_helper.py

示例8: get_vocab_files

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
def get_vocab_files(vocabprefix):
    #Get list of files for vocabulary
    vocab_uri = URIRef("http://vocab.ox.ac.uk/%s"%vocabprefix)
    vocabdir = os.path.join(ag.vocabulariesdir, vocabprefix)
    vocabstatusfile = os.path.join(vocabdir, "status.rdf")
    vocab_files = {}
    if not os.path.isfile(vocabstatusfile):
        return vocab_files
    graph = Graph()
    graph.parse(vocabstatusfile)
    for v in graph.objects(None, namespaces['dcterms']['hasFormat']):
        v_str = str(v)
        vocab_files[v_str] = {'name':'', 'format':'', 'path':''}

        for f in graph.objects(URIRef(v), namespaces['dcterms']['format']):
            vocab_files[v_str]['format'] = str(f)
        for n in graph.objects(URIRef(v), namespaces['nfo']['fileName']):
            vocab_files[v_str]['name'] = str(n)
        for p in graph.objects(URIRef(v), namespaces['nfo']['fileUrl']):
            vocab_files[v_str]['path'] = str(p).replace('file://', '')
    return vocab_files
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:23,代码来源:rdf_helper.py

示例9: __init__

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
class Store:
    def __init__(self):
        self.graph = ConjunctiveGraph()
        if os.path.exists(storefn):
            self.graph.load(storeuri, format='n3')
        self.graph.bind('dc', DC)
        self.graph.bind('foaf', FOAF)
        self.graph.bind('imdb', IMDB)
        self.graph.bind('rev', 'http://purl.org/stuff/rev#')

    def save(self):
        self.graph.serialize(storeuri, format='n3')

    def who(self, who=None):
        if who is not None:
            name, email = (r_who.match(who).group(1), r_who.match(who).group(2))
            self.graph.add((URIRef(storeuri), DC['title'], Literal(title % name)))
            self.graph.add((URIRef(storeuri + '#author'), RDF.type, FOAF['Person']))
            self.graph.add((URIRef(storeuri + '#author'),
                            FOAF['name'], Literal(name)))
            self.graph.add((URIRef(storeuri + '#author'),
                            FOAF['mbox'], Literal(email)))
            self.save()
        else:
            return self.graph.objects(URIRef(storeuri + '#author'), FOAF['name'])

    def new_movie(self, movie):
        movieuri = URIRef('http://www.imdb.com/title/tt%s/' % movie.movieID)
        self.graph.add((movieuri, RDF.type, IMDB['Movie']))
        self.graph.add((movieuri, DC['title'], Literal(movie['title'])))
        self.graph.add((movieuri, IMDB['year'], Literal(int(movie['year']))))
        self.save()

    def new_review(self, movie, date, rating, comment=None):
        review = BNode()  # @@ humanize the identifier (something like #rev-$date)
        movieuri = URIRef('http://www.imdb.com/title/tt%s/' % movie.movieID)
        self.graph.add((movieuri, REV['hasReview'], URIRef('%s#%s' % (storeuri, review))))
        self.graph.add((review, RDF.type, REV['Review']))
        self.graph.add((review, DC['date'], Literal(date)))
        self.graph.add((review, REV['maxRating'], Literal(5)))
        self.graph.add((review, REV['minRating'], Literal(0)))
        self.graph.add((review, REV['reviewer'], URIRef(storeuri + '#author')))
        self.graph.add((review, REV['rating'], Literal(rating)))
        if comment is not None:
            self.graph.add((review, REV['text'], Literal(comment)))
        self.save()

    def movie_is_in(self, uri):
        return (URIRef(uri), RDF.type, IMDB['Movie']) in self.graph
开发者ID:RDFLib,项目名称:rdflib,代码行数:51,代码来源:film.py

示例10: get_vocab_description

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
def get_vocab_description(vocabfile, vocabprefix):
    if not os.path.isfile(vocabfile):
        return {}
    graph = Graph()
    try:
        graph.parse(vocabfile)
    except:
        graph = None
        graph = Graph()
        try:
            graph.parse(vocabfile, format="n3")
        except:
            return {}
    descriptions = defaultdict(list)
    base = None
    properties = get_vocab_properties(vocabprefix)
    if 'preferredNamespaceUri' in properties and properties['preferredNamespaceUri']:
        base = properties['preferredNamespaceUri']
    else:
        (id, base, prefix) = get_vocab_base(vocabfile)
    if base:
        for k, predicates in vocab_description_uri.iteritems():
            for p in predicates:
                vals = None
                vals = graph.objects(URIRef(base), p)
                for val in vals:
                    if not val in descriptions[k]:
                        descriptions[k].append(val)
    for k, predicates in vocab_description.iteritems():
        if not k in descriptions or not descriptions[k]:
            for p in predicates:
                vals = graph.objects(None, p)
                for val in vals:
                    if not val in descriptions[k]:
                        descriptions[k].append(val)
    return dict(descriptions)
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:38,代码来源:rdf_helper.py

示例11: get_vocab_editorial_note

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
def get_vocab_editorial_note(vocabprefix):
    vocab_uri = URIRef("http://vocab.ox.ac.uk/%s"%vocabprefix)
    vocabdir = os.path.join(ag.vocabulariesdir, vocabprefix)
    vocabstatusfile = os.path.join(vocabdir, "status.rdf")
    msgs = []
    if not os.path.isfile(vocabstatusfile):
        return msgs
    graph = Graph()
    graph.parse(vocabstatusfile)
    for s, p, o in graph.triples((None, namespaces['skos']['editorialNote'], None)):
        nm = None
        for n in graph.objects(URIRef(s), namespaces['nfo']['fileName']):
            nm = str(n)
        msgs.append((str(o), nm))
    return msgs
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:17,代码来源:rdf_helper.py

示例12: get_influence_links

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
def get_influence_links():
    for wp_url in set(list(G.subjects())):
        m = re.match("https://en.wikipedia.org/wiki/(.+)", wp_url)
        if not m:
            continue
        title = m.group(1)
        dbpedia_url = URIRef('http://dbpedia.org/resource/%s' % title)
        dbp = ConjunctiveGraph()
        dbp.parse(dbpedia_url)

        for o in dbp.objects(dbpedia_url, dbpedia.influencedBy):
            m = re.match("http://dbpedia.org/resource/(.+)$", o)
            if not m: 
                continue
            wp_url2 = URIRef("https://en.wikipedia.org/wiki/" + m.group(1))
            if len(list(G.predicate_objects(wp_url2))) > 0:
                G.add((wp_url, dbpedia.influencedBy, wp_url2))
开发者ID:edsu,项目名称:parisreview,代码行数:19,代码来源:crawl.py

示例13: handle

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
    def handle(self, **options):
        _logger.debug("linking places")
        for place in models.Place.objects.filter(dbpedia__isnull=True):
            if not place.city or not place.state:
                continue

            # formulate a dbpedia place uri
            path = urllib2.quote('%s,_%s' % (_clean(place.city), 
                                             _clean(place.state)))
            url = URIRef('http://dbpedia.org/resource/%s' % path)

            # attempt to get a graph from it
            graph = ConjunctiveGraph()
            try: 
                _logger.debug("looking up %s" % url)
                graph.load(url)
            except urllib2.HTTPError, e:
                _logger.error(e)

            # if we've got more than 3 assertions extract some stuff from 
            # the graph and save back some info to the db, would be nice
            # to have a triple store underneath where we could persist
            # all the facts eh?

            if len(graph) >= 3:
                place.dbpedia = url
                place.latitude = graph.value(url, geo['lat'])
                place.longitude = graph.value(url, geo['long'])
                for object in graph.objects(URIRef(url), owl['sameAs']):
                    if object.startswith('http://sws.geonames.org'):
                        place.geonames = object
                place.save()
                _logger.info("found dbpedia resource %s" % url)
            else:
                _logger.warn("couldn't find dbpedia resource for %s" % url)

            reset_queries()
开发者ID:open-oni,项目名称:open-oni,代码行数:39,代码来源:link_places.py

示例14: Inspector

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
class Inspector(object):

    """ Class that includes methods for querying an RDFS/OWL ontology """

    def __init__(self, uri, language=""):
        super(Inspector, self).__init__()
        self.rdfGraph = ConjunctiveGraph()
        try:
            self.rdfGraph.parse(uri, format="application/rdf+xml")
        except:
            try:
                self.rdfGraph.parse(uri, format="n3")
            except:
                raise exceptions.Error("Could not parse the file! Is it a valid RDF/OWL ontology?")
        finally:
            self.baseURI = self.get_OntologyURI() or uri
            self.allclasses = self.__getAllClasses(includeDomainRange=True, includeImplicit=True, removeBlankNodes=False, excludeRDF_OWL=False)

    def get_OntologyURI(self, return_as_string=True):
        test = [x for x, y, z in self.rdfGraph.triples((None, RDF.type, Ontology))]
        if test:
            if return_as_string:
                return str(test[0])
            else:
                return test[0]
        else:
            return None

    def __getAllClasses(self, classPredicate="", includeDomainRange=False, includeImplicit=False, removeBlankNodes=True, addOWLThing=True, excludeRDF_OWL=True):

        rdfGraph = self.rdfGraph
        exit = {}

        def addIfYouCan(x, mydict):
            if excludeRDF_OWL:
                if x.startswith('http://www.w3.org/2002/07/owl#') or  \
                   x.startswith("http://www.w3.org/1999/02/22-rdf-syntax-ns#") or \
                   x.startswith("http://www.w3.org/2000/01/rdf-schema#"):
                    return mydict
            if x not in mydict:
                mydict[x] = None
            return mydict

        if addOWLThing:
            exit = addIfYouCan(Thing, exit)

        if classPredicate == "rdfs" or classPredicate == "":
            for s in rdfGraph.subjects(RDF.type, RDFS.Class):
                exit = addIfYouCan(s, exit)

        if classPredicate == "owl" or classPredicate == "":
            for s in rdfGraph.subjects(RDF.type, Class):
                exit = addIfYouCan(s, exit)

        if includeDomainRange:
            for o in rdfGraph.objects(None, RDFS.domain):
                exit = addIfYouCan(o, exit)
            for o in rdfGraph.objects(None, RDFS.range):
                exit = addIfYouCan(o, exit)

        if includeImplicit:
            for s, v, o in rdfGraph.triples((None, RDFS.subClassOf, None)):
                exit = addIfYouCan(s, exit)
                exit = addIfYouCan(o, exit)
            for o in rdfGraph.objects(None, RDF.type):
                exit = addIfYouCan(o, exit)

        # get a list
        exit = exit.keys()
        if removeBlankNodes:
            exit = [x for x in exit if not isBlankNode(x)]
        return sort_uri_list_by_name(exit)

    def __getTopclasses(self, classPredicate=''):
        returnlist = []

        for eachclass in self.__getAllClasses(classPredicate):
            x = self.get_classDirectSupers(eachclass)
            if not x:
                returnlist.append(eachclass)
        return sort_uri_list_by_name(returnlist)

    def __getTree(self, father=None, out=None):
        if not father:
            out = {}
            topclasses = self.toplayer
            out[0] = topclasses

            for top in topclasses:
                children = self.get_classDirectSubs(top)
                out[top] = children
                for potentialfather in children:
                    self.__getTree(potentialfather, out)

            return out

        else:
            children = self.get_classDirectSubs(father)
            out[father] = children
            for ch in children:
#.........这里部分代码省略.........
开发者ID:rmoorman,项目名称:encoded,代码行数:103,代码来源:generate_ontology.py

示例15: URIRef

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import objects [as 别名]
# step 1: find all the classes.
rdftype = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
rdfsdomain = URIRef("http://www.w3.org/2000/01/rdf-schema#domain")
rdfsrange = URIRef("http://www.w3.org/2000/01/rdf-schema#range")
rdfsresource = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#Resource")
rdfssco = URIRef("http://www.w3.org/2000/01/rdf-schema#subClassOf")
asColl = URIRef("http://www.w3.org/ns/activitystreams#OrderedCollection")
skosConcept = URIRef("http://www.w3.org/2004/02/skos/core#Concept")

otherClasses = [asColl, skosConcept]
classes = list(g.subjects(rdftype, URIRef("http://www.w3.org/2000/01/rdf-schema#Class")))
props = list(g.subjects(rdftype, URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#Property")))

for p in props:
    domains = list(g.objects(p, rdfsdomain))
    for d in domains:
        assert(d in classes)

for p in props:
    ranges = list(g.objects(p, rdfsrange))
    for r in ranges:
        if not r in classes and not str(r).startswith("http://www.w3.org/2001/XMLSchema#") and \
            not r == rdfsresource:
            print "Found inconsistent property: %s has unknown range" % p

for c in classes:
    parents = list(g.objects(c, rdfssco))
    for p in parents:
        if not p in classes and not p in otherClasses:
            print "Found inconsistent class: %s has unknown superClass" % c
开发者ID:AutomatedTester,项目名称:web-platform-tests,代码行数:32,代码来源:vocab_tester.py


注:本文中的rdflib.ConjunctiveGraph.objects方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。