• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python graph.Graph类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: _new_sioc_post

    def _new_sioc_post(self, topic_uri, recipient_uri):
        """ Create a new rdf/xml sioc:Post based on a topic, and for a given recipient.
            Timestamp is set to now, and sender is taken from WebID authenticated person (TBC). """

        uri = self.message_uri_prefix + uuid.uuid1().hex

        graph = Graph()
        graph.add(
            (rdflib.URIRef(uri),
             rdflib.URIRef("http://xmlns.com/foaf/0.1/primaryTopic"),
             rdflib.URIRef(topic_uri)))

        graph.add(
            (rdflib.URIRef(uri),
             rdflib.URIRef("http://rdfs.org/sioc/ns#addressed_to"),
             rdflib.URIRef(recipient_uri)))

        graph.add(
            (rdflib.URIRef(uri),
             rdflib.URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
             rdflib.URIRef(self.sioc_ns+"Post")))

        graph.add(
            (rdflib.URIRef(uri),
             rdflib.URIRef("http://purl.org/dc/terms/created"),
             rdflib.Literal(strftime("%Y-%m-%dT%H:%M:%SZ")))) # FIXME forces zulu time, which may be technically incorrect
        
        rdf = graph.serialize(format="xml") # rdf/xml
        return {"rdf": rdf, "uri": uri}
开发者ID:electronicmax,项目名称:webbox-core,代码行数:29,代码来源:webboxhandler.py


示例2: _find_graph

 def _find_graph(self):
     if self._is_dbpedia_uri():
         return SPARQLGraph('http://dbpedia.org/sparql')
     else:
         graph = Graph()
         graph.parse(self.uri)
         return graph
开发者ID:lyndonnixon,项目名称:LSI,代码行数:7,代码来源:linkeddata.py


示例3: testIssue29

    def testIssue29(self):
        input = """@prefix foo-bar: <http://example.org/> .

foo-bar:Ex foo-bar:name "Test" . """

        g = Graph()
        g.parse(data=input, format="n3")
开发者ID:suzuken,项目名称:xbrlparser,代码行数:7,代码来源:test_n3.py


示例4: harvest_collection

def harvest_collection(col_url, col_uri, store_host, manifest_file=None):
    store_host = clean_store_host(store_host)
    with transaction.commit_on_success():        
        col_g = Graph(store=rdfstore(), identifier=URIRef(col_uri))
        collection.fetch_and_parse(col_url, col_g, manifest_file=manifest_file)
        localize_describes(store_host, col_uri, col_url, col_g)

        res_uris_urls = collection.aggregated_uris_urls(col_uri, col_g)
        for res_uri, res_url in res_uris_urls:
            res_g = Graph(store=rdfstore(), identifier=URIRef(res_uri))
            collection.fetch_and_parse(res_url, res_g)
            for pred in col_res_attributes:
                for t in res_g.triples((res_uri, pred, None)):
                    col_g.add(t)

            aggr_uris_urls = collection.aggregated_uris_urls(res_uri, res_g)
            for aggr_uri, aggr_url in aggr_uris_urls:
                if aggr_url:
                    collection.fetch_and_parse(aggr_url, res_g)
                    localize_describes(store_host, aggr_uri, aggr_url, res_g)
                    localize_describes(store_host, aggr_uri, aggr_url, col_g)

            seq_uris_urls = collection.aggregated_seq_uris_urls(res_uri, res_g)
            for seq_uri, seq_url in seq_uris_urls:
                page_uris_urls = collection.aggregated_uris_urls(seq_uri, res_g)
                for page_uri, page_url in page_uris_urls:
                    localize_describes(store_host, page_uri, page_url, res_g)
            localize_describes(store_host, res_uri, res_url, res_g)
            localize_describes(store_host, res_uri, res_url, col_g)
开发者ID:bobclewell,项目名称:DM,代码行数:29,代码来源:_harvest.py


示例5: testGraphIntersection

    def testGraphIntersection(self):
        g1 = Graph()
        g2 = Graph()

        g1.add((self.tarek, self.likes, self.pizza))
        g1.add((self.michel, self.likes, self.cheese))

        g2.add((self.bob, self.likes, self.cheese))
        g2.add((self.michel, self.likes, self.cheese))

        g3 = g1 * g2

        self.assertEquals(len(g3), 1)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g3, False)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.michel, self.likes, self.cheese) in g3, True)

        g1 *= g2

        self.assertEquals(len(g1), 1)

        self.assertEquals((self.tarek, self.likes, self.pizza) in g1, False)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.michel, self.likes, self.cheese) in g1, True)
开发者ID:DarioGT,项目名称:rdflib-django,代码行数:30,代码来源:test_rdflib.py


示例6: enhance

    def enhance(self, content, input=Format.TEXT, output=Format.JSON):
        analysis = self.status["analyses"][0]
        params = {
            self.param_in: input.name,
            self.param_out: output.name
        }
        resource = self._build_url("/%s/%s/%s" % (self.path, analysis, self.enhance_path), params)
        logging.debug("Making request to %s" % resource)

        response = self._post(resource, content, input.mimetype, output.mimetype)

        if response.status_code != 200:
            logging.error("Enhance request returned %d: %s" % (response.status_code, response.reason))
            return response.text
        else:
            contentType = from_mimetype(response.headers["Content-Type"])
            if contentType == Format.JSON or contentType == Format.REDLINKJSON:
                return json.loads(response.text)
            elif contentType == Format.XML or contentType == Format.REDLINKXML:
                return minidom.parse(response.text)
            elif contentType.rdflibMapping:
                g = Graph()
                g.parse(data=response.text, format=contentType.rdflibMapping)
                return g
            else:
                logging.warn("Handler not found for %s, so returning raw text response..." % contentType.mimetype)
                return response.text
开发者ID:insideout10,项目名称:redlink-python-sdk,代码行数:27,代码来源:analysis.py


示例7: fromuri2

    def fromuri2(self, uri):

        self.uri = uri

        if not uri.startswith('http://rdf.freebase.com'):
            self.checkuri()
            try:
                g = Graph()
                g.parse(self.uri)

                if g:
                    logger.info("INFO process_rdf.py - returning graph for " + self.uri)
                    return g

                else:
                    raise Exception('Nothing was returned, probably caused URL serving no RDF or bad RDF (eg. Freebase): '
                                    '"No handlers could be found for logger "process_rdf.py" -- uri was ' + self.uri)

            except URLError as e:
                logger.error("URLError process_rdf.py - " + e.message)
                raise Exception('URLError, cause either bad URL or no internet connection - ' + e.message + '(uri was ' + self.uri + ')')
            except SAXParseException as e:
                logger.error("SAXParseException process_rdf.py - " + e.message + '(uri was' + self.uri + ')')
                raise Exception('SAXParseException')
            except AttributeError as e:
                logger.error("AttributeError process_rdf.py - " + e.message + '(uri was' + self.uri + ')')
                raise Exception('AttributeError')
        else:
            self.fromfreebaseuri()
开发者ID:geekscruff,项目名称:peoplesparql,代码行数:29,代码来源:process_rdf.py


示例8: read_project

def read_project(request, project_uri):
    """Returns a HttpResponse of the cached project metadata graph"""
    project_uri = URIRef(project_uri)

    if request.user.is_authenticated():
        if permissions.has_permission_over(project_uri, user=request.user, permission=NS.perm.mayRead):
            identifier = uris.uri('semantic_store_projects', uri=project_uri)
            store_metadata_graph = get_project_metadata_graph(project_uri)
            ret_graph = Graph()
            ret_graph += store_metadata_graph

            add_is_described_bys(request, project_uri, ret_graph)

            for permission in ProjectPermission.objects.filter(identifier=project_uri):
                user = permission.user
                user_uri = uris.uri('semantic_store_users', username=user.username)
                perm_uri = permissions.PERMISSION_URIS_BY_MODEL_VALUE[permission.permission]

                ret_graph += user_metadata_graph(user=user)
                ret_graph.add((user_uri, NS.perm.hasPermissionOver, project_uri))
                ret_graph.add((user_uri, perm_uri, project_uri))
            
            if len(ret_graph) > 0:
                return NegotiatedGraphResponse(request, ret_graph)
            else:
                return HttpResponseNotFound()
        else:
            return HttpResponseForbidden('User "%s" does not have read permissions over project "%s"' % (request.user.username, project_uri))
    else:
        return HttpResponse(status=401)
开发者ID:timandres,项目名称:DM,代码行数:30,代码来源:projects.py


示例9: delete_triples_from_project

def delete_triples_from_project(request, uri):
    """Deletes the triples in a graph provided by a request object from the project graph.
    Returns an HttpResponse of all the triples which were successfully removed from the graph."""
    if request.user.is_authenticated():
        if permissions.has_permission_over(uri, user=request.user, permission=NS.perm.mayUpdate):
            removed = Graph()
            bind_namespaces(removed)

            try:
                g = parse_request_into_graph(request)
            except (ParserError, SyntaxError) as e:
                return HttpResponse(status=400, content="Unable to parse serialization.\n%s" % e)

            project_g = get_project_graph(uri)
            project_metadata_g = get_project_metadata_graph(uri)

            for t in g:
                if t in project_g:
                    project_g.remove(t)
                    removed.add(t)
                project_metadata_g.remove(t)

            return NegotiatedGraphResponse(request, removed)
        else:
            return HttpResponseForbidden('User "%s" does not have update permissions over project "%s"' % (request.user.username, uri))
    else:
        return HttpResponse(status=401)
开发者ID:timandres,项目名称:DM,代码行数:27,代码来源:projects.py


示例10: Processor

class Processor(object):
    def __init__(self, stream_urls):
        self.client = client.Client(stream_urls,
                                    event_callback=self._handle_event,
                                    error_callback=self._handle_error,
                                    separate_events=False)
        self.triple_store = Graph('Sleepycat',
                                  'http://www.it.uc3m.es/jaf/ns/slog/db')
        self.db_dir = 'dbdir'

    def start(self, loop=False):
        self.triple_store.open(self.db_dir)
        self.client.start(loop=loop)

    def stop(self):
        self.triple_store.close()
        self.client.stop()

    def _handle_error(self, message, http_error=None):
        pass

    def _handle_event(self, evs):
        print('Received {} events.'.format(len(evs)))
        for event in evs:
            self.triple_store += event.body
        print(len(self.triple_store))
开发者ID:jfisteus,项目名称:ztreamy,代码行数:26,代码来源:processor.py


示例11: test_c

def test_c():
    """Test reading N3 from a codecs.StreamReader, outputting unicode"""
    g = Graph()
#    rdf_reader.seek(0)
    g.parse(source=rdf_reader, format='n3')
    v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
    assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr')
开发者ID:drewp,项目名称:rdflib,代码行数:7,代码来源:test_issue084.py


示例12: NegationOfAtomicConcept

class NegationOfAtomicConcept(unittest.TestCase):
    def setUp(self):
        self.ontGraph = Graph()
        self.ontGraph.bind('ex', EX_NS)
        self.ontGraph.bind('owl', OWL_NS)
        Individual.factoryGraph = self.ontGraph

    def testAtomicNegation(self):
        bar=EX.Bar
        baz=~bar
        baz.identifier = EX_NS.Baz
        ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
        individual=BNode()
        individual2=BNode()
        (EX.OtherClass).extent = [individual]
        bar.extent = [individual2]
        NormalFormReduction(self.ontGraph)
        self.assertEqual(repr(baz),
                         "Class: ex:Baz DisjointWith ex:Bar\n")
        posRules,negRules=CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Foo])
        self.failUnless(not posRules,"There should be no rules in the 0 strata!")
        self.failUnless(len(negRules)==1,"There should only be one negative rule in a higher strata")
        self.assertEqual(repr(negRules[0]),
                         "Forall ?X ( ex:Baz(?X) :- not ex:Bar(?X) )")
        baz.graph = network.inferredFacts
        self.failUnless(individual in baz.extent,
                        "%s should be a member of ex:Baz"%individual)
        self.failUnless(individual2 not in baz.extent,
                        "%s should *not* be a member of ex:Baz"%individual2)
开发者ID:carnotip,项目名称:FuXi,代码行数:29,代码来源:Negation.py


示例13: NegatedDisjunctTest

class NegatedDisjunctTest(unittest.TestCase):
    def setUp(self):
        self.ontGraph = Graph()
        self.ontGraph.bind('ex', EX_NS)
        self.ontGraph.bind('owl', OWL_NS)
        Individual.factoryGraph = self.ontGraph

    def testStratified(self):
        bar=EX.Bar
        baz=EX.Baz
        noBarOrBaz = ~(bar|baz)
        omega = EX.Omega
        foo = omega & noBarOrBaz
        foo.identifier = EX_NS.Foo
        ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
        individual=BNode()
        omega.extent = [individual]
        NormalFormReduction(self.ontGraph)
        self.assertEqual(repr(foo),
                         "ex:Omega that ( not ex:Bar ) and ( not ex:Baz )")
        posRules,negRules=CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Foo])
        foo.graph = network.inferredFacts
        self.failUnless(not posRules,"There should be no rules in the 0 strata!")
        self.assertEqual(repr(negRules[0]),"Forall ?X ( ex:Foo(?X) :- And( ex:Omega(?X) not ex:Bar(?X) not ex:Baz(?X) ) )")
        self.failUnless(len(negRules)==1,"There should only be one negative rule in a higher strata")
        self.failUnless(individual in foo.extent,
                        "%s should be a member of ex:Foo"%individual)
开发者ID:carnotip,项目名称:FuXi,代码行数:27,代码来源:Negation.py


示例14: setUp

    def setUp(self):
        self.graph1 = Graph(store=self.store_name)
        self.graph2 = Graph(store=self.store_name)

        self.graph1.open(self.settings1, True)
        self.graph2.open(self.settings2, True)

        self.oNS = Namespace("http://www.example.org/rdf/things#")
        self.sNS = Namespace("http://www.example.org/rdf/people#")
        self.pNS = Namespace("http://www.example.org/rdf/relations/")

        self.graph1.bind('people',self.sNS)
        self.graph1.bind('relations',self.pNS)
        self.graph1.bind('things',self.oNS)
        self.graph2.bind('people',self.sNS)
        self.graph2.bind('relations',self.pNS)
        self.graph2.bind('things',self.oNS)

        self.michel = self.sNS.michel
        self.tarek = self.sNS.tarek
        self.alice = self.sNS.alice
        self.bob = self.sNS.bob
        self.likes = self.pNS.likes
        self.hates = self.pNS.hates
        self.named = self.pNS.named
        self.pizza = self.oNS.pizza
        self.cheese = self.oNS.cheese
开发者ID:handloomweaver,项目名称:agamemnon,代码行数:27,代码来源:test_rdf.py


示例15: open

 def open(self, configuration, create=False):
     """Raise a ModificationException if create, as this graph is read-only.
     """
     if create:
         raise ModificationException() #ReadOnlyGraph does not support this
     else:
         Graph.open(self, configuration, create)
开发者ID:ktbs,项目名称:ktbs,代码行数:7,代码来源:__init__.py


示例16: test_xml_e

def test_xml_e():
    """Test reading XML from a BytesIO created from utf8 encoded string"""
    g = Graph()
    g.parse(source=BytesIO(rdfxml_utf8), format='xml')
    v = g.value(subject=URIRef("http://www.test.org/#CI"),
                predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
    assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr')
开发者ID:RDFLib,项目名称:rdflib,代码行数:7,代码来源:test_issue084.py


示例17: GraphAggregates2

class GraphAggregates2(unittest.TestCase):
    # known_issue = True

    def setUp(self):
        memStore = plugin.get("SQLAlchemy", Store)(identifier="rdflib_test", configuration=Literal("sqlite://"))
        self.graph1 = Graph(memStore, URIRef("http://example.com/graph1"))
        self.graph2 = Graph(memStore, URIRef("http://example.com/graph2"))
        self.graph3 = Graph(memStore, URIRef("http://example.com/graph3"))

        for n3Str, graph in [(testGraph1N3, self.graph1), (testGraph2N3, self.graph2), (testGraph3N3, self.graph3)]:
            graph.parse(StringIO(n3Str), format="n3")
        self.graph4 = Graph(memStore, RDFS.uri)
        self.graph4.parse(RDFS.uri)
        self.G = ConjunctiveGraph(memStore)

    def testAggregateSPARQL(self):
        raise SkipTest("known_issue with SELECT from NAMED")
        rt = self.G.query(sparqlQ)
        assert len(rt) > 1
        rt = self.G.query(sparqlQ2, initBindings={u"?graph": URIRef(u"http://example.com/graph3")})
        try:
            import json

            assert json
        except ImportError:
            import simplejson as json
        res = json.loads(rt.serialize(format="json").decode("utf-8"))
        assert len(res["results"]["bindings"]) == 20, len(res["results"]["bindings"])
开发者ID:RDFLib,项目名称:rdflib-sqlalchemy,代码行数:28,代码来源:test_aggregate_graphs.py


示例18: test_b

def test_b():
    """Test reading N3 from a utf8 encoded string as data"""
    g = Graph()
    g.parse(data=rdf_utf8, format='n3')
    v = g.value(subject=URIRef("http://www.test.org/#CI"),
                predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
    assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr')
开发者ID:RDFLib,项目名称:rdflib,代码行数:7,代码来源:test_issue084.py


示例19: test_rdf

def test_rdf(mfile):
    g = Graph()
    try:
        g = g.parse(mfile, format='xml')
        return True
    except Exception as inst:
        return False
开发者ID:benosteen,项目名称:RDFDatabank,代码行数:7,代码来源:misc.py


示例20: test_e

def test_e():
    """Test reading N3 from a BytesIO over the string object"""
    g = Graph()
    g.parse(source=BytesIO(rdf_utf8), format='n3')
    v = g.value(subject=URIRef("http://www.test.org/#CI"),
                predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
    assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr')
开发者ID:RDFLib,项目名称:rdflib,代码行数:7,代码来源:test_issue084.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python namespace.NamespaceManager类代码示例发布时间:2022-05-26
下一篇:
Python graph.ConjunctiveGraph类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap