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


Python ConjunctiveGraph.parse方法代码示例

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


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

示例1: check_type_definitions

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
def check_type_definitions(vocabfile):
    graph = Graph()
    try:
        graph.parse(vocabfile)
    except:
        return False
    all_definitions = True
    
    testo = vocab_type_definitions_test['rdfs']
    subjects = []
    subs = graph.subjects(namespaces['rdf']['type'], URIRef(testo))
    for s in subs:
        subjects.append(s)
    if subjects:
        objects = vocab_type_definitions_rdfs
    else:
        objects = vocab_type_definitions_owl
    for o in objects: 
        subs = graph.subjects(namespaces['rdf']['type'], o)
        done = []
        for s in subs:
            if s in done:
               continue
            done.append(s) 
            definition = False
            vals = graph.objects(s, namespaces['rdfs']['isDefinedBy'])
            for val in vals:
               definition = True
            all_definitions = all_definitions and definition
    return all_definitions
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:32,代码来源:conversion_helper_rdf.py

示例2: check_propeties

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
def check_propeties(vocabfile):
    graph = Graph()
    try:
        graph.parse(vocabfile)
    except:
        return {}

    subject = none
    for s in graph.subjects(namespaces['dc']['title'], None):
        subject = s
    if not subject:
        for s in graph.subjects(namespaces['dcterms']['title'], None):
            subject = s
    if not subject:
        for s in graph.subjects(namespaces['dc']['creator'], None):
            subject = s
    if not subject:
        for s in graph.subjects(namespaces['dcterms']['creator'], None):
            subject = s

    properties = {}

    #Identifier
    identifier = []
    ids = graph.objects(subject, namespaces['dc']['identifier'])
    for id in ids:
        identifier = id
    if not identifier:
        ids = graph.objects(subject, namespaces['dcterms']['identifier'])
        for id in ids:
            identifier.append(id)
    properties['identifier'] = [id]
    
    #hasFormat
    format = False
    
    prop1 = True
    prop2 = False
    prop3 = False
    properties['format'] = []
    for fm in graph.objects(subject, namespaces['dcterms']['hasFormat']):
        properties['format'].append(fm)
        bnodes = graph.objects(fm, namespaces['dc']['format'])
        for b in bnodes:
            for value in graph.objects(b, namespaces['rdf']['value']):
                prop1 = True
            for value in graph.objects(b, namespaces['rdfs']['label']):
                prop2 = True
            for value in graph.objects(b, namespaces['rdfs']['type']):
                prop3 = True
        if not 'all' in properties:
            properties['all'] = prop1 and prop2 and prop3
        else:
            properties['all'] = properties['all'] and prop1 and prop2 and prop3

    conforms = False
    if identifier and properties['format'] and properties['all']:
         conforms = True
    
    return (conforms, properties)
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:62,代码来源:conversion_helper_rdf.py

示例3: getGraph

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
def getGraph():
    """
    get the main graph, including data from trains.n3 on disk
    """
    graph = ConjunctiveGraph()
    graph.parse("trains.n3", format="n3", publicID=TT['disk#context'])
    return graph
开发者ID:drewp,项目名称:traintimes,代码行数:9,代码来源:localrdf.py

示例4: readGraphs

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
def readGraphs():
    g = ConjunctiveGraph()
    # this file should only be reread when it changes
    g.parse("../config.n3", format="n3")
    dl = []
    startTime = time.time()
    for uri in [
        "http://bang:9055/graph",
        "http://bang:9069/graph",
        "http://bang:9070/graph",
        "http://bang:9072/bang-9002/processStatus",
        "http://bang:9072/bang/processStatus",
        "http://bang:9072/dash/processStatus",
        "http://bang:9072/slash-11000/processStatus",
        "http://bang:9072/slash/processStatus",
        "http://bang:9072/star/processStatus",
        "http://bang:9075/graph",
        ]:
        # this ought to not reparse the ones that are 304 not modified
        d = getPage(uri)
        def done(trig, uri):
            g.addN(parseTrig(trig))
            print "%s done in %.02fms" % (uri, 1000 * (time.time() - startTime))
        d.addCallback(done, uri)
        dl.append(d)
    return defer.DeferredList(dl).addCallback(lambda result: g)
开发者ID:drewp,项目名称:magma,代码行数:28,代码来源:sensorstate.py

示例5: main

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
def main():
	"""Main Function
	Simple command-line procedure for web2rdf."""

	if len(sys.argv) != 2:
		print "Must call with a URI parameter."
		print "Usage: %s uriSrc" % sys.argv[0]
		return

	uri = sys.argv[1]

	# Get the RDF
	wrdf = Web2Rdf(uri)
	rdf = wrdf.getRdf()

	if not rdf:
		print "No RDF returned!"
		return False

	print "Got RDF..."
	rdf = rdfString(rdf)

	# Open Storage
	print "Opening store..."
	db = "./testdb.sqlite"
	rstore = RdfStore('sqlite', db)
	rstore.open()

	print "Storing..."
	graph = Graph(rstore.get(), identifier = URIRef("http://slashdot/Test2"))
	#graph.parse("example.rdf")
	graph.parse(rdf, publicID=uri)

	graph.commit()
开发者ID:spsu,项目名称:web2rdf,代码行数:36,代码来源:fetch.py

示例6: parse

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
 def parse(self, result):
     """
     Parse query result
     
     @param result: text result
     @return: rdf graph
     """        
     graph = ConjunctiveGraph()
     graph.parse(StringInputSource(result))
     return graph
开发者ID:BackupTheBerlios,项目名称:swaml-svn,代码行数:12,代码来源:sparlclient.py

示例7: testModel

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
    def testModel(self):
        g = ConjunctiveGraph()
        g.parse(StringInputSource(input), format="n3")
        i = 0
        for s, p, o in g:
            if isinstance(s, Graph):
                i += 1
        self.assertEquals(i, 3)
        self.assertEquals(len(list(g.contexts())), 13)

        g.close()
开发者ID:AuroraSkywalker,项目名称:watchdog,代码行数:13,代码来源:n3.py

示例8: del_vocab_from_creator

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
def del_vocab_from_creator(userid, vocab):
    if not os.path.isfile(os.path.join(ag.creatorsdir, '%s.rdf'%userid)):
        return False
    graph = Graph()
    graph.parse(os.path.join(ag.creatorsdir, '%s.rdf'%userid))
    vocab_uri = URIRef("http://vocab.ox.ac.uk/%s"%vocabprefix)
    for s, p, o in graph.triples((URIRef(vocab_uri), namespaces['dcterms']['mediator'], None)):
        graph.remove((s, p, o))
    rdf_str = None
    rdf_str = graph.serialize()
    f = codecs.open(creatorfile, 'w', 'utf-8')
    f.write(rdf_str)
    f.close()
    return True 
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:16,代码来源:conversion_helper_rdf.py

示例9: testQueryingMore

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
 def testQueryingMore(self):
     for result in self.results:
         uri = result[0]
         g = ConjunctiveGraph()
         g.parse(uri)
         query = Parse("""
                             SELECT ?person
                             WHERE {
                                      <%s> foaf:primaryTopic ?person .
                                      ?person rdf:type foaf:Person . 
                                   }
                       """ % uri )
         queryResults = g.query(query, initNs=NSbindings).serialize('python')
         if (len(queryResults)>0):
             self.assertEquals(str(queryResults[0]), "http://www.wikier.org/foaf#wikier")
开发者ID:BackupTheBerlios,项目名称:swaml-svn,代码行数:17,代码来源:sindice.py

示例10: TestSPARQLToldBNodes

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
class TestSPARQLToldBNodes(unittest.TestCase):
    def setUp(self):
        NS = u"http://example.org/"
        self.graph = ConjunctiveGraph()
        self.graph.parse(StringInputSource("""
           @prefix    : <http://example.org/> .
           @prefix rdf: <%s> .
           @prefix rdfs: <%s> .
           [ :prop :val ].
           [ a rdfs:Class ]."""%(RDF.RDFNS,RDFS.RDFSNS)), format="n3")
    def testToldBNode(self):
        for s,p,o in self.graph.triples((None,RDF.type,None)):
            pass
        query = """SELECT ?obj WHERE { %s ?prop ?obj }"""%s.n3()
        print query
        rt = self.graph.query(query)
        self.failUnless(len(rt) == 1,"BGP should only match the 'told' BNode by name (result set size: %s)"%len(rt))
开发者ID:Ju2ender,项目名称:watchdog,代码行数:19,代码来源:test_sparql_told_bnodes.py

示例11: main

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
def main(specloc, template, mode="spec"):
    """The meat and potatoes: Everything starts here."""

    m = Graph()
    m.parse(specloc)

#    m = RDF.Model()
#    p = RDF.Parser()
#    p.parse_into_model(m, specloc)
    
    classlist, proplist = specInformation(m)
    
    if mode == "spec":
        # Build HTML list of terms.
        azlist = buildazlist(classlist, proplist)
    elif mode == "list":
        # Build simple <ul> list of terms.
        azlist = build_simple_list(classlist, proplist)

    # Generate Term HTML
#    termlist = "<h3>Classes and Properties (full detail)</h3>"
    termlist = docTerms('Class',classlist,m)
    termlist += docTerms('Property',proplist,m)
    
    # Generate RDF from original namespace.
    u = urllib.urlopen(specloc)
    rdfdata = u.read()
    rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata)
    rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata)
    rdfdata.replace("""<?xml version="1.0"?>""", "")
    
    # print template % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata.encode("ISO-8859-1"))
    #template = re.sub(r"^#format \w*\n", "", template)
    #template = re.sub(r"\$VersionInfo\$", owlVersionInfo(m).encode("utf-8"), template) 
    
    # NOTE: This works with the assumtpion that all "%" in the template are escaped to "%%" and it
    #       contains the same number of "%s" as the number of parameters in % ( ...parameters here... )

    print "AZlist",azlist
    print "Termlist",termlist
 
#xxx    template = template % (azlist.encode("utf-8"), termlist.encode("utf-8"));    
#    template += "<!-- specification regenerated at " + time.strftime('%X %x %Z') + " -->"
    
    return template
开发者ID:foaf,项目名称:foaftown,代码行数:47,代码来源:specgen4b.py

示例12: load_store

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
 def load_store(files):
     """
    Takes a directory of RDf files and loads them into the store.
    """
     try:
         store = plugin.get("MySQL", Store)("rdflib_db")
         store.open(config["rdflib.config"])
         graph = ConjunctiveGraph(store)
         # iterate through files and load them into the graph
         for fpath in fl:
             graph.parse(fpath, format=get_format(fpath), publicID=context_uri(fpath))
             print fpath + " loaded."
         # save triples to store
         graph.commit()
         graph.close()
     except:
         print "=== error opening RDF store ==="
         exit
开发者ID:bdarcus,项目名称:mysite,代码行数:20,代码来源:rdf_store.py

示例13: testSPARQLNotEquals

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
def testSPARQLNotEquals():
    NS = u"http://example.org/"
    graph = ConjunctiveGraph()
    graph.parse(StringInputSource("""
       @prefix    : <http://example.org/> .
       @prefix rdf: <%s> .
       :foo rdf:value 1.
       :bar rdf:value 2."""%RDF.RDFNS), format="n3")
    rt = graph.query("""SELECT ?node 
                        WHERE {
                                ?node rdf:value ?val.
                                FILTER (?val != 1)
                               }""",
                           initNs={'rdf':RDF.RDFNS},                           
                           DEBUG=False)
    for row in rt:        
        item = row[0]
        assert item == URIRef("http://example.org/bar")
开发者ID:Ju2ender,项目名称:watchdog,代码行数:20,代码来源:test_not_equals.py

示例14: getRdfXml

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
def getRdfXml(rdf):
    n3 = ""
    
    # Append the RDF namespace and print the prefix namespace mappings
    rdf['namespaces']['xh1'] = "http://www.w3.org/1999/xhtml/vocab#"
    rdf['namespaces']['rdf'] = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    for prefix, uri in rdf['namespaces'].items():
        n3 += "@prefix %s: <%s> .\n" % (prefix, uri)
        
    # Print each subject-based triple to the screen
    triples = rdf['triples']
    processed = []

    # Get all of the non-bnode subjects
    nonBnodeSubjects = getNonBnodeSubjects(triples)

    # Get all of the bnode subjects
    bnodeSubjects = getBnodeSubjects(triples)

    for subject in nonBnodeSubjects:
        subjectTriples = getTriplesBySubject(subject, triples)
        #print "PROCESSING NB SUBJECT:", subjectTriples

        if(subject not in processed):
            n3 += tripleToN3(subjectTriples, processed, triples)
        processed.append(subject)

    for subject in bnodeSubjects:
        subjectTriples = getTriplesBySubject(subject, triples)
        #print "PROCESSING BN SUBJECT:", subject
        if(subject not in processed):
            n3 += bnodeToN3(subjectTriples, processed, triples)
            n3 += " .\n"

    #print n3

    g = ConjunctiveGraph()
    g.parse(StringIO(n3), format="n3")
    rdfxml = g.serialize()

    return rdfxml
开发者ID:davidlehn,项目名称:librdfa-old,代码行数:43,代码来源:rdfa2rdfxml.py

示例15: testParse

# 需要导入模块: from rdflib.Graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.Graph.ConjunctiveGraph import parse [as 别名]
 def testParse(self):
     g = ConjunctiveGraph()
     g.parse("http://groups.csail.mit.edu/dig/2005/09/rein/examples/troop42-policy.n3", format="n3")
开发者ID:AuroraSkywalker,项目名称:watchdog,代码行数:5,代码来源:n3.py


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