本文整理匯總了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
示例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)
示例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
示例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)
示例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()
示例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
示例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()
示例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
示例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")
示例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))
示例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
示例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
示例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")
示例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
示例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")