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


Python Graph.objects方法代码示例

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


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

示例1: handle

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
    def handle(self, *args, **options):
        from rdflib.graph import Graph
        from rdflib import RDFS, RDF, OWL
        from rdflib.term import URIRef, BNode, Literal
        import yaml

        OboDefinition = URIRef('http://purl.obolibrary.org/obo/IAO_0000115')
        part_of_some = URIRef('http://purl.obolibrary.org/obo/BFO_0000050_some')
        Synonym = URIRef(u'http://www.geneontology.org/formats/oboInOwl#hasSynonym')

        g = Graph()
        g.parse(args[1], 'xml')

        Model = MuscleOwl if args[0] == 'm' else BehaviorOwl

        # first pass, add the things
        for subject in nonblankthings(g, g.subjects()):
            slabel = g.label(subject)
            m = get_model_instance(Model, unicode(subject))
            m.uri = unicode(subject)
            m.label = unicode(slabel)

            m.rdfs_is_class = (subject, RDF.type, OWL.Class) in g
            m.obo_definition = unicode(g.value(subject, OboDefinition, None))
            m.rdfs_comment = unicode(g.value(subject, RDFS.comment, None))
            synonyms = [unicode(syn) for syn in g.objects(subject, Synonym)]
            if len(synonyms):
                m.synonyms_comma_separated = ", ".join(synonyms)
            else:
                m.synonyms_comma_separated = None

            m.save()

        # second pass, add the relationships
        for subject in nonblankthings(g, g.subjects()):
            slabel = g.label(subject)
            m = Model.objects.get(uri=unicode(subject))

            m.rdfs_subClassOf_ancestors.clear()
            # add all super-classes to m.rdfs_subClassOf_ancestors
            for obj in nonblankthings(g, g.transitive_objects(subject, RDFS.subClassOf)):
                if obj != subject:
                    a = Model.objects.get(uri=unicode(obj))
                    m.rdfs_subClassOf_ancestors.add(a)

            m.bfo_part_of_some.clear()
            # add all things that this thing is part of to m.bfo_part_of_some
            for obj in nonblankthings(g, g.objects(subject, part_of_some)):
                if obj != subject:
                    a = Model.objects.get(uri=unicode(obj))
                    m.bfo_part_of_some.add(a)

            # add only direct super-classes to m.rdfs_subClassOf
            #for obj in nonblankthings(g, g.objects(subject, RDFS.subClassOf)):
            #    if obj != subject:
            #        a = Model.objects.get(uri=unicode(obj))
            #        m.rdfs_subClassOf.add(a)

            m.save()
开发者ID:NESCent,项目名称:feedingdb,代码行数:61,代码来源:loadowl.py

示例2: json

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
    def json(self,rdf_content):
        """Parse the RDF file in Lightbase format and returns it 
        in a json format        
        """
        g = Graph()
        
        lb = Namespace('http://rdf.lightbase.cc/ontology/')
        dc = Namespace('http://purl.org/dc/elements/1.1/')
        
        #print(rdf_content)
        
        result = g.parse(data=rdf_content, format="application/rdf+xml")
        
        self.rdf_collection = json_for_graph(result)
        self.rdf_identifier = g.objects(None,dc['identifier']).next().toPython()

        # Get base name here
        self.base_name = g.objects(None,lb['baseName']).next()
                  
        # Test with SPARQL        
        teste = result.query(
                             """
                             PREFIX lb: <http://rdf.lightbase.cc/ontology/> 
                             PREFIX dc: <http://purl.org/dc/elements/1.1/>
                             SELECT ?fieldName ?fieldData
                             WHERE {
                                 ?x lb:fieldName ?fieldName .
                                 ?x dc:description ?fieldData .                                 
                                }
                             """
                             )
        
        # I need one specific field
        arquivo = result.query("""
                                PREFIX lb: <http://rdf.lightbase.cc/ontology/>
                                PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                                SELECT ?arquivo
                                WHERE {
                                    ?x rdf:type lb:registro .
                                    ?x lb:arquivo ?arquivo .
                                }                               
                               """)
        
        # Return metadata as dict
        self.metadata = dict(teste.result)
        self.metadata['url'] = arquivo.result[0]
        self.metadata['id'] = self.rdf_identifier
开发者ID:lightbase,项目名称:ckanext-lightbase,代码行数:49,代码来源:rdf.py

示例3: parse

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
    def parse(self,rdf_content):
        """Parse the RDF file in Lightbase format
        This method returns a dict where the first index is the index and the 
        second is another dict, containing register identifier and the RDF document
        itself
        """
        g = Graph()
        
        lb = Namespace('http://rdf.lightbase.cc/ontology/')
        dc = Namespace('http://purl.org/dc/elements/1.1/')
        
        result = g.parse(data=rdf_content, format="application/rdf+xml")
        self.rdf_collection = result.serialize(format='turtle')
        self.rdf_identifier = g.objects(None,dc['identifier']).next().toPython()

        # Get base name here
        self.base_name = g.objects(None,lb['baseName']).next()
        
        # Test with SPARQL        
        teste = result.query(
                             """
                             PREFIX lb: <http://rdf.lightbase.cc/ontology/> 
                             PREFIX dc: <http://purl.org/dc/elements/1.1/>
                             SELECT ?fieldName ?fieldData
                             WHERE {
                                 ?x lb:fieldName ?fieldName .
                                 ?x dc:description ?fieldData .
                                }
                             """
                             )
        
        
        # I need one specific field
        arquivo = result.query("""
                                PREFIX lb: <http://rdf.lightbase.cc/ontology/>
                                PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                                SELECT ?arquivo
                                WHERE {
                                    ?x rdf:type lb:registro .
                                    ?x lb:arquivo ?arquivo .
                                }                               
                               """)
        
        # Return metadata as tuple
        self.metadata = dict(teste.result)
        self.metadata['url'] = arquivo.result[0]
        self.metadata['id'] = self.rdf_identifier
开发者ID:lightbase,项目名称:ckanext-lightbase,代码行数:49,代码来源:rdf.py

示例4: traverse

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
 def traverse(s, depth=0, graph=None):
     if graph is None:
         graph = Graph()
         [ graph.bind(prefix, uri) 
           for prefix, uri in settings.NAMESPACES.items() ]
     graph += cg.triples((s,None,None))
     if depth > 0:
         map(partial(traverse, depth=depth-1, graph=graph), 
             set(graph.objects(subject=s)))
     return graph
开发者ID:editorsnotes,项目名称:django-graphs,代码行数:12,代码来源:views.py

示例5: ExampleGraph

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
class ExampleGraph(object):
    '''Class representing a NIDM-Results examples graph to be compared to some
    ground truth graph'''

    def __init__(self, name, owl_file, ttl_file, gt_ttl_files,
                 exact_comparison):
        self.name = name
        self.ttl_file = ttl_file

        self.owl_file = owl_file
        self.gt_ttl_files = gt_ttl_files
        self.exact_comparison = exact_comparison
        self.graph = Graph()
        self.graph.parse(ttl_file, format='turtle')

        # Get NIDM-Results version for each example
        versions = self.graph.objects(None, NIDM_VERSION)
        assert versions is not None
        self.version = str(versions.next())

        if self.version != "dev":
            self.gt_ttl_files = [
                x.replace(os.path.join("nidm", "nidm"),
                          os.path.join("nidm_releases", self.version, "nidm"))
                for x in self.gt_ttl_files]
            self.owl_file = os.path.join(
                os.path.dirname(owl_file),
                "releases",
                "nidm-results_"+self.version.replace(".", "")+".owl")

        owl_imports = None
        if self.version == "dev":
            owl_imports = glob.glob(
                os.path.join(os.path.dirname(owl_file),
                             os.pardir, os.pardir, "imports", '*.ttl'))
        self.owl = OwlReader(self.owl_file, owl_imports)
开发者ID:adshereen,项目名称:nidm,代码行数:38,代码来源:TestResultDataModel.py

示例6: RIFCoreParser

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
class RIFCoreParser(object):
    def __init__(self, location=None, graph=None, debug=False):
        self.location = location
        self.rules = {}
        if graph:
            assert location is None, "Must supply one of graph or location"
            self.graph = graph
            if debug:
                _debug("RIF in RDF graph was provided")
        else:
            assert graph is None, "Must supply one of graph or location"
            if debug:
                _debug("RIF document URL provided %s" % location)
            if self.location.find('http:') + 1:
                req = urllib2.Request(self.location)

                #From:
                #http://www.diveintopython.org/http_web_services/redirects.html
                # points an 'opener' to the address to 'sniff' out final
                # Location header
                opener = urllib2.build_opener(SmartRedirectHandler())
                f = opener.open(req)
                self.content = f.read()
            else:
                self.content = urllib2.urlopen(self.location).read()
                # self.content = open(self.location).read()
            try:
                transform = etree.XSLT(etree.parse(TRANSFORM_URI))
                self.graph = Graph().parse(
                    data=etree.tostring(
                        transform(etree.fromstring(self.content))))
                if debug:
                    _debug("Extracted rules from RIF XML format")
            except ValueError:
                try:
                    self.graph = Graph().parse(data=self.content, format='xml')
                except:
                    self.graph = Graph().parse(data=self.content, format='n3')
                if debug:
                    _debug("Extracted rules from RIF in RDF document")

    def getRuleset(self):
        """
        >>> parser = RIFCoreParser('http://www.w3.org/2005/rules/test/repository/tc/Frames/Frames-premise.rif')
        >>> for rule in parser.getRuleset(): print(rule)
        Forall ?Customer ( ns1:discount(?Customer 10) :- ns1:status(?Customer "gold"^^<http://www.w3.org/2001/XMLSchema#string>) )
        Forall ?Customer ( ns1:discount(?Customer 5) :- ns1:status(?Customer "silver"^^<http://www.w3.org/2001/XMLSchema#string>) )
        >>> parser = RIFCoreParser('http://www.w3.org/2005/rules/test/repository/tc/Guards_and_subtypes/Guards_and_subtypes-premise.rif')
        >>> for rule in parser.getRuleset(): print(rule)
        """
        self.implications = dict([(impl, (body, bodyType, head, headType))
                                    for impl, body, bodyType, head, headType in
                                        self.graph.query(IMPLIES_PARTS, initNs=rif_namespaces)])
        self.rules = dict([(rule, (vars, impl))
                                for rule, vars, impl
                                    in self.graph.query(RULE_PARTS,
                                                        initNs=rif_namespaces)])
        self.frames = dict([(frame, (obj, slots))
            for frame, obj, slots in self.graph.query(FRAME_PARTS,
                                                    initNs=rif_namespaces)])

        self.atoms = dict([(atom, (args, op))
                                for atom, args, op in self.graph.query(
                                        ATOM_PARTS,
                                        initNs=rif_namespaces)])

        self.externals = dict([(external, (args, op))
                               for external, args, op in self.graph.query(
                                    EXTERNAL_PARTS,
                                    initNs=rif_namespaces)])
        rt = []
        for sentenceCollection in self.graph.objects(predicate=RIF_NS.sentences):
            col = Collection(self.graph, sentenceCollection)
            for sentence in col:
                if RIF_NS.Implies in self.graph.objects(sentence, RDF.type):
                    rt.append(self.extractImp(sentence))
                elif RIF_NS.Forall in self.graph.objects(sentence, RDF.type):
                    rt.append(self.extractRule(sentence))
        return rt

    def extractImp(self, impl):
        body, bodyType, head, headType = self.implications[impl]
        head = first(self.extractPredication(head, headType))
        if bodyType == RIF_NS.And:
            raise
        else:
            body = self.extractPredication(body, bodyType)

        body = And([first(body)]) if len(body) == 1 else And(body)
        return Rule(Clause(body, head), declare=[])

    def extractRule(self, rule):
        vars, impl = self.rules[rule]
        body, bodyType, head, headType = self.implications[impl]
        allVars = map(self.extractTerm, Collection(self.graph, vars))
        head = first(self.extractPredication(head, headType))
        if bodyType == RIF_NS.And:
            body = [first(self.extractPredication(
                       i,
                       first(self.graph.objects(i, RDF.type)))
#.........这里部分代码省略.........
开发者ID:Web5design,项目名称:FuXi,代码行数:103,代码来源:RIFCore.py

示例7: main

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]

#.........这里部分代码省略.........
        if options.builtins:
            import imp
            userFuncs = imp.load_source('builtins', options.builtins)
            rs = HornFromN3(fileN,
                            additionalBuiltins=userFuncs.ADDITIONAL_FILTERS)
            nsBinds.update(rs.nsMapping)
        elif options.ruleFormat == 'rif':
            try:
                from FuXi.Horn.RIFCore import RIFCoreParser
                rif_parser = RIFCoreParser(location=fileN, debug=options.debug)
                rs = rif_parser.getRuleset()
            except ImportError:
                raise Exception(
                    "Missing 3rd party libraries for RIF processing"
                )
        else:
            rs = HornFromN3(fileN)
        nsBinds.update(rs.nsMapping)
        ruleSet.formulae.extend(rs)
        #ruleGraph.parse(fileN,format='n3')

    ruleSet.nsMapping = nsBinds

    for prefix, uri in list(nsBinds.items()):
        namespace_manager.bind(prefix, uri, override=False)
    closureDeltaGraph = Graph()
    closureDeltaGraph.namespace_manager = namespace_manager
    factGraph.namespace_manager = namespace_manager

    if not options.sparqlEndpoint:
        for fileN in facts:
            factGraph.parse(fileN, format=options.inputFormat)
            if options.imports:
                for owlImport in factGraph.objects(predicate=OWL_NS.imports):
                    factGraph.parse(owlImport)
                    print("Parsed Semantic Web Graph.. %s" % owlImport)

    if not options.sparqlEndpoint and facts:
        for pref, uri in factGraph.namespaces():
            nsBinds[pref]=uri

    if options.stdin:
        assert not options.sparqlEndpoint, "Cannot use --stdin with --sparqlEndpoint"
        factGraph.parse(sys.stdin, format=options.inputFormat)

    #Normalize namespace mappings
    #prune redundant, rdflib-allocated namespace prefix mappings
    newNsMgr = NamespaceManager(factGraph)
    from FuXi.Rete.Util import CollapseDictionary
    for k, v in list(CollapseDictionary(dict([(k, v)
                                    for k, v in factGraph.namespaces()])).items()):
        newNsMgr.bind(k, v)
    factGraph.namespace_manager = newNsMgr

    if options.normalForm:
        NormalFormReduction(factGraph)

    if not options.sparqlEndpoint:
        workingMemory = generateTokenSet(factGraph)
    if options.builtins:
        import imp
        userFuncs = imp.load_source('builtins', options.builtins)
        rule_store, rule_graph, network = SetupRuleStore(
                             makeNetwork=True,
                             additionalBuiltins=userFuncs.ADDITIONAL_FILTERS)
    else:
开发者ID:baojie,项目名称:FuXi-1,代码行数:70,代码来源:CommandLine.py

示例8: Graph

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
g = Graph()

# Bind a few prefix, namespace pairs.
g.bind("dc", "http://http://purl.org/dc/elements/1.1/")
g.bind("foaf", "http://xmlns.com/foaf/0.1/")

# Create a namespace object for the Friend of a friend namespace.
FOAF = Namespace("http://xmlns.com/foaf/0.1/")

# Create an identifier to use as the subject for Donna.
donna = BNode()

# Add triples using store's add method.
g.add((donna, RDF.type, FOAF["Person"]))
g.add((donna, FOAF["nick"], Literal("donna", lang="foo")))
g.add((donna, FOAF["name"], Literal("Donna Fales")))

# Iterate over triples in store and print them out.
print("--- printing raw triples ---")
for s, p, o in g:
    print((s, p, o))

# For each foaf:Person in the store print out its mbox property.
print("--- printing mboxes ---")
for person in g.subjects(RDF.type, FOAF["Person"]):
    for mbox in g.objects(person, FOAF["mbox"]):
        print(mbox)
        
        
开发者ID:huanjiayang,项目名称:SWoT,代码行数:29,代码来源:main.py

示例9: __init__

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]

#.........这里部分代码省略.........
		'''	
		for place in rss.getElementsByTagName('place'):
			name1 = place.getElementsByTagName('name1')[0].firstChild.nodeValue
			blogger_id1 = place.getElementsByTagName('blogger-id')[0].firstChild.nodeValue
			title1 = place.getElementsByTagName('title')[0].firstChild.nodeValue
			url1 = place.getElementsByTagName('url')[0].firstChild.nodeValue
			date1 = place.getElementsByTagName('date')[0].firstChild.nodeValue
			expense = place.getElementsByTagName('expense')[0].firstChild.nodeValue
			
			
			blog  = self.nsDict['blog']
			foaf = self.nsDict['foaf']
			dcterms = self.nsDict['dcterms'] 
			self.graph.add((blog,blogger_id1,Literal(blogger_id1)))
			self.graph.add((blog[blogger_id1],foaf['name'],Literal(name1)))
			self.graph.add((blog[blogger_id1],dcterms['title'],Literal(title1)))
			self.graph.add((blog[blogger_id1],dcterms['date'],Literal(date1)))
		'''
			
		self.graph.commit()

	def open_store(self):
		default_graph_uri = "http://rdflib.net/rdfstore"
		# open existing store or create new one
		#store = getStore() # if store does not exist, then new store returned
		
		# RDF store section:
		configString = "/var/tmp/rdfstore"
		
		# Get the Sleepycat plugin.
		store = plugin.get('Sleepycat', Store)('rdfstore')		
		# Open previously created store, or create it if it doesn't exist yet
		path = mkdtemp()
		rt = store.open('rdfstore', create=False)
		#print rt
		#print path
		
		if rt == NO_STORE:
			print "Creating new store"
			# There is no underlying Sleepycat infrastructure, create it
			store.open('rdfstore', create=True)        
		else:
			print "store exists "
			#assert rt == VALID_STORE, "The underlying store is corrupt"

		self.graph = Graph(store,identifier = URIRef(default_graph_uri))		
		self.build_graph()	
		        				        
		'''
		print_RDF_triples(graph)
		#print_RDF_XML(graph)
		graph.commit()
		#create_RDF_File(graph)
		graph.close(commit_pending_transaction=True)

		'''

	def run_Query(self,queryString):
		qres = self.graph.query(queryString,
							initNs=dict(foaf=Namespace("http://xmlns.com/foaf/0.1/"),
							blog = Namespace('http://rdflib.net/blog/'),
							blogger_id = Namespace('http://rdflib.net/blog/blogger_id/'))
							)
		for row in qres.result:
			print row
	
	
	def print_RDF_XML(self):
	    #print graph.serialize(format="pretty-xml")
	    print self.graph.serialize()

	def print_RDF_triples(self):
		print "Triples in graph after add: ", len(graph)
		
		#Iterate over triples in graph and print them out.
		print "--- printing raw triples ---"
		for s, p, o in self.graph:
		        print s, p, o

	def print_RDF_Maker(self):
	    # For each foaf:Project in the self.graph print out its maker.
	    print "--- printing MAKERS ---"
	    for game in self.graph.subjects(RDF.type, FOAF["Project"]):
	            for madeby in self.graph.objects(game, FOAF["maker"]):
	                    print madeby
			
	def removeFromStore(self):
		rdflib = Namespace('http://rdflib.net/games/')
		self.graph.bind("game", "http://rdflib.net/games/")
		self.graph.remove((rdflib['game:2'], rdflib['name'], Literal('Ignition')))
		self.graph.commit()
		#str(graph)

	def sample_query(self, querystring):
	    print "Query enter"
	    processor = plugin.get('sparql', rdflib.query.Processor)(self.graph)
	    result = plugin.get('sparql', rdflib.query.Result)
	    
	    ns = dict(self.graph.namespace_manager.namespaces())
	    return result(processor.query(querystring, initNs=ns))
开发者ID:shreeshga,项目名称:BlogCrawler,代码行数:104,代码来源:rdflibmethods.py

示例10: BuildNaturalSIP

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]

#.........这里部分代码省略.........
    ( <http://doi.acm.org/10.1145/28659.28689#up> <http://doi.acm.org/10.1145/28659.28689#sg> <http://doi.acm.org/10.1145/28659.28689#flat> ) ( ?Z3 )
    ( <http://doi.acm.org/10.1145/28659.28689#up> <http://doi.acm.org/10.1145/28659.28689#sg> ) ( ?Z1 )

    >>> sip = BuildNaturalSIP(list(rs)[-1], [MAGIC.sg], None)  #doctest: +SKIP
    >>> list(sip.query('SELECT ?q {  ?prop a magic:SipArc . [] ?prop ?q . }', initNs={%(u)s'magic':MAGIC}))  #doctest: +SKIP
    [rdflib.term.URIRef(%(u)s'http://doi.acm.org/10.1145/28659.28689#sg'), rdflib.term.URIRef(%(u)s'http://doi.acm.org/10.1145/28659.28689#sg')]
    """
    from FuXi.Rete.Magic import AdornedUniTerm
    occurLookup = {}
    boundHead = isinstance(
        adornedHead, AdornedUniTerm) and 'b' in adornedHead.adornment
    phBoundVars = list(adornedHead.getDistinguishedVariables(varsOnly=True))
    # assert isinstance(clause.head, Uniterm), "Only one literal in the head."

    def collectSip(left, right):
        if isinstance(left, list):
            vars = CollectSIPArcVars(left, right, phBoundVars)
            if not vars and ignoreUnboundDPreds:
                raise InvalidSIPException("No bound variables for %s" % right)
            leftList = Collection(sipGraph, None)
            left = list(set(left))
            [leftList.append(i) for i in [GetOp(ii) for ii in left]]
            left.append(right)
            # arc = SIPGraphArc(leftList.uri, getOccurrenceId(right, occurLookup), vars, sipGraph)
            return left
        else:
            left.isHead = True
            vars = CollectSIPArcVars(left, right, phBoundVars)
            if not vars and ignoreUnboundDPreds:
                raise InvalidSIPException("No bound variables for %s" % right)
            ph = GetOp(left)
            # q = getOccurrenceId(right, occurLookup)
            if boundHead:
                # arc = SIPGraphArc(ph, q, vars, sipGraph, headPassing=boundHead)
                sipGraph.add((ph, RDF.type, MAGIC.BoundHeadPredicate))
                rt = [left, right]
            else:
                rt = [right]
        return rt
    sipGraph = Graph()
    if isinstance(clause.body, And):
        if ignoreUnboundDPreds:
            foundSip = False
            sips = findFullSip(([clause.head], None), clause.body)
            while not foundSip:
                sip = next(sips) if py3compat.PY3 else sips.next()
                try:
                    reduce(collectSip,
                           iterCondition(And(sip)))
                    foundSip = True
                    bodyOrder = sip
                except InvalidSIPException:
                    foundSip = False
        else:
            if first(filter(lambda i: isinstance(i, Uniterm) and i.naf or False,
                            clause.body)):
                # There are negative literals in body, ensure
                # the given sip order puts negated literals at the end
                bodyOrder = first(
                    filter(ProperSipOrderWithNegation,
                           findFullSip(([clause.head], None),
                                       clause.body)))
            else:
                bodyOrder = first(
                    findFullSip(([clause.head], None), clause.body))
            assert bodyOrder, "Couldn't find a valid SIP for %s" % clause
            reduce(collectSip,
                   iterCondition(And(bodyOrder)))
        sipGraph.sipOrder = And(bodyOrder[1:])
        # assert validSip(sipGraph), sipGraph.serialize(format='n3')
    else:
        if boundHead:
            reduce(collectSip, itertools.chain(iterCondition(clause.head),
                                               iterCondition(clause.body)))
        sipGraph.sipOrder = clause.body
    if derivedPreds:
        # We therefore generalize our notation to allow
        # more succint representation of sips, in which only arcs entering
        # derived predicates are represented.
        arcsToRemove = []
        collectionsToClear = []
        for N, prop, q in sipGraph.query(
                'SELECT ?N ?prop ?q {  ?prop a magic:SipArc . ?N ?prop ?q . }',
                initNs={u'magic': MAGIC}):
            if occurLookup[q] not in derivedPreds and (
                occurLookup[
                    q] not in hybridPreds2Replace if hybridPreds2Replace else False
            ):
                arcsToRemove.extend([(N, prop, q), (prop, None, None)])
                collectionsToClear.append(Collection(sipGraph, N))
                # clear bindings collection as well
                bindingsColBNode = first(
                    sipGraph.objects(prop, MAGIC.bindings))
                collectionsToClear.append(
                    Collection(sipGraph, bindingsColBNode))
        for removeSts in arcsToRemove:
            sipGraph.remove(removeSts)
        for col in collectionsToClear:
            col.clear()
    return sipGraph
开发者ID:RDFLib,项目名称:FuXi,代码行数:104,代码来源:SidewaysInformationPassing.py

示例11: gmtime

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
timeString=strftime("%Y-%m-%d", gmtime())
print "Starting yummyRobot : "+timeString
d = os.path.join(dataDir,timeString)
if not os.path.exists(d):
	os.makedirs(d)

scriptsDir=os.path.join(os.getcwd(),"yummyScripts");
configData=Graph()
for confFile in os.listdir(scriptsDir): 
	if confFile.endswith('.ttl'):
		configData.parse(os.path.join(scriptsDir,confFile),format="turtle");
print "checking Modules : "
triples=configData.triples((None,RDF.type,scriptClass))
for (s,p,o) in triples:
	commands=configData.objects(s,hasCommandProperty)
	for command in commands:
		scriptsCommands[s]=command
	labels=configData.objects(s,RDFS.label)
	for label in labels:
		scriptsLabels[s]=label
	print "Found "+s+" ("+scriptsLabels[s]+") @ "+scriptsCommands[s]
		

tStoresDesc=Graph()
tStoresDesc.parse("../Resources/EndPointList.ttl",format="turtle");

triples=tStoresDesc.triples((None,RDF.type,endpointClass))

for (s,p,o) in triples:
		endpointURLStats=tStoresDesc.objects(s,hasEndpointProperty);
开发者ID:sgtp,项目名称:yummydata,代码行数:32,代码来源:yummyMain.py

示例12: Literal

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
# -- (part 2) manually add a triple to the graph --
g.add((URIRef(u"http://example.com/bar"), RDFS.label, Literal("bar")))

# NOTE: predicat RDFS.label will be extended as a full URI: http://www.w3.org/2000/01/rdf-schema#label

# bind a namespace prefix for the example URI reference
g.bind("ex", "http://example.com/")

# serialise the graph in the Turtle RDF syntax
print g.serialize(destination=None, format="turtle", base=None, encoding=None)


# -- (part 3) parse XML/RDF data provided in a string into the graph store --
print "Number of triples in the graph: %i" % len(g)
g.parse(data=rdf_xml_data, format="application/rdf+xml")
print "Number of triples in the graph after parsing the string: %i" % len(g)

# check the actual namespaces bound in the graph store
# NOTE: there should be one additional namespace after parsing the string
for ns in g.namespaces():
    print "Prefix: %s => URI: %s" % ns

# serialise the graph
print "\nContents of Graph store in Turtle format:\n========================================\n"
print g.serialize(destination=None, format="turtle")

# manually retrieve the names of artists stored in a graph
for artist in g.objects(subject=None, predicate=URIRef("http://www.recshop.fake/cd#artist")):
    print artist
开发者ID:uansett,项目名称:SemWeb,代码行数:31,代码来源:graphQuery.py

示例13: BNode

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
donna = BNode()

# Add triples using store's add method.
store.add((donna, RDF.type, FOAF["Person"]))
store.add((donna, FOAF["nick"], Literal("donna", lang="foo")))
store.add((donna, FOAF["name"], Literal("Donna Fales")))

# Iterate over triples in store and print them out.
print("--- printing raw triples ---")
for s, p, o in store:
    print((s, p, o))

# For each foaf:Person in the store print out its mbox property.
print("--- printing mboxes ---")
for person in store.subjects(RDF.type, FOAF["Person"]):
    for mbox in store.objects(person, FOAF["mbox"]):
        print(mbox)

# Serialize the store as RDF/XML to the file foaf.rdf.
# store.serialize("foaf.rdf", format="pretty-xml", max_depth=3)

# Let's show off the serializers

print("RDF Serializations:")

# Serialize as XML
print("--- start: rdf-xml ---")
print(store.serialize(format="pretty-xml"))
print("--- end: rdf-xml ---\n")

# Serialize as NTriples
开发者ID:SpazioDati,项目名称:rdflib,代码行数:33,代码来源:simple_example.py

示例14: main

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]

#.........这里部分代码省略.........
        factGraph = Graph(plugin.get('SPARQLStore', Store)(facts[0]))
        options.hybrid = False
    else:
        factGraph = Graph()
    ruleSet = Ruleset()

    for fileN in options.rules:
        if options.ruleFacts and not options.sparqlEndpoint:
            factGraph.parse(fileN, format='n3')
            print("Parsing RDF facts from ", fileN)
        if options.builtins:
            import imp
            userFuncs = imp.load_source('builtins', options.builtins)
            rs = HornFromN3(fileN,
                            additionalBuiltins=userFuncs.ADDITIONAL_FILTERS)
        else:
            rs = HornFromN3(fileN)
        nsBinds.update(rs.nsMapping)
        ruleSet.formulae.extend(rs)
        #ruleGraph.parse(fileN, format='n3')

    ruleSet.nsMapping = nsBinds

    for prefix, uri in list(nsBinds.items()):
        namespace_manager.bind(prefix, uri, override=False)
    closureDeltaGraph = Graph()
    closureDeltaGraph.namespace_manager = namespace_manager
    factGraph.namespace_manager = namespace_manager

    if not options.sparqlEndpoint:
        for fileN in facts:
            factGraph.parse(fileN, format=options.inputFormat)
            if options.imports:
                for owlImport in factGraph.objects(predicate=OWL_NS.imports):
                    factGraph.parse(owlImport)
                    print("Parsed Semantic Web Graph.. ", owlImport)

        if facts:
            for pref, uri in factGraph.namespaces():
                nsBinds[pref] = uri

    if options.stdin:
        assert not options.sparqlEndpoint, (
            "Cannot use --stdin with --sparqlEndpoint")
        factGraph.parse(sys.stdin, format=options.inputFormat)

    # Normalize namespace mappings
    # prune redundant, rdflib-allocated namespace prefix mappings
    new_ns_mgr = NamespaceManager(factGraph)
    from FuXi.Rete.Util import CollapseDictionary
    for k, v in CollapseDictionary(dict([(k, v) for k, v in
                                   factGraph.namespaces()])).items():
        new_ns_mgr.bind(k, v)
    factGraph.namespace_manager = new_ns_mgr

    if options.normalForm:
        NormalFormReduction(factGraph)

    if not options.sparqlEndpoint:
        workingMemory = generateTokenSet(factGraph)
    if options.builtins:
        import imp
        userFuncs = imp.load_source('builtins', options.builtins)
        rule_store, rule_graph, network = SetupRuleStore(
            makeNetwork=True, additionalBuiltins=userFuncs.ADDITIONAL_FILTERS)
    else:
开发者ID:nuoya,项目名称:FuXi,代码行数:70,代码来源:CommandLine.py

示例15: Namespace

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import objects [as 别名]
##--------------------##
# Checking keywords in objectives
graphUSDL4EDU=Graph()
graphUSDL4EDU.parse("\commondata\usdl4edu.ttl",format='n3')
USDL4EDU = Namespace("http://rdf.genssiz.dei.uc.pt/usdl4edu#")
DC = Namespace("http://purl.org/dc/terms/")


graphConcepts=Graph()
graphConcepts.parse("\commondata\exported\context.ttl",format='n3')
SKOS = Namespace("http://www.w3.org/2004/02/skos/core#")

keywords=[]
for obj in graphUSDL4EDU.subjects(RDF.type,USDL4EDU["KnowledgeDimension"]):
	# aux=[]
	for mbox in graphUSDL4EDU.objects(obj,USDL4EDU["hasKeyword"]):
		# aux.append(str(mbox))
		keywords.append(str(mbox))
		print mbox
print keywords
# graph=Graph()
# graph.parse("\commondata\exported\udacity.ttl",format='n3')
# description=""
# number_descriptions=0
# number_found=0
# number_context=0
# for obj in graph.subjects(RDF.type,USDL4EDU["OverallObjective"]):
# 	for mbox in graph.objects(obj,DC["description"]):
# 		number_descriptions+=1
# 		# if obj==URIRef(USDL4EDU["Organizao-Comportamento-Conhecimento-e-Inovao-objectives"]):
# 		# 	description=mbox
开发者ID:jduro,项目名称:esoteric,代码行数:33,代码来源:rdf_test.py


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