本文整理汇总了Python中rdflib.graph.Graph.serialize方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.serialize方法的具体用法?Python Graph.serialize怎么用?Python Graph.serialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.graph.Graph
的用法示例。
在下文中一共展示了Graph.serialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RdfJsonSerializerTestCase
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
class RdfJsonSerializerTestCase(unittest.TestCase):
identifier = "rdflib_test"
def setUp(self):
self.graph = Graph()
def test_serialize_xml(self):
self.graph.parse(data=json_data, format="rdf-json")
res = self.graph.serialize(format="xml")
g2 = Graph()
g2.parse(data=rdf_data)
self.assert_(self.graph.isomorphic(g2))
log.debug("XML")
log.debug(res)
self.assert_(
'''rdf:nodeID="na's Homepage"''' not in str(res) \
and '''rdf:nodeID="na Wilder"''' not in str(res))
def test_roundtrip_json(self):
self.graph.parse(data=json_data, format="rdf-json")
res = self.graph.serialize(format="rdf-json")
g2 = Graph()
g2.parse(data=res, format="rdf-json")
log.debug("RDFJSON")
log.debug(res)
self.assert_(len(self.graph) == 12 and len(g2) == 12)
self.assert_(self.graph.isomorphic(g2))
self.assert_(
'''"_:na's Homepage"''' not in str(res) \
and '''"value": "_:na Wilder"''' not in str(res))
示例2: team_index
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def team_index(request, format=None):
logging.info("Format: %s" % format)
if format == None:
best_match = mimeparse.best_match(['application/rdf+xml', 'application/rdf+n3', 'text/html'], request.META['HTTP_ACCEPT'])
if best_match == 'application/rdf+xml':
format = 'rdf+xml'
elif best_match == 'application/rdf+nt':
format = 'rdf+nt'
else:
format = 'html'
team_list = College.objects.filter(updated=True).order_by('name')
if ( format != 'html'):
store = Graph()
store.bind("cfb", "http://www.cfbreference.com/cfb/0.1/")
CFB = Namespace("http://www.cfbreference.com/cfb/0.1/")
for current_team in team_list:
team = BNode()
store.add((team, RDF.type, CFB["Team"]))
store.add((team, CFB["name"], Literal(current_team.name)))
store.add((team, CFB["link"], Literal(current_team.get_absolute_url())))
if ( format == 'rdf+xml'):
return HttpResponse(store.serialize(format="pretty-xml"), mimetype='application/rdf+xml')
if ( format == 'rdf+nt'):
return HttpResponse(store.serialize(format="nt"), mimetype='application/rdf+nt')
return render_to_response('college/teams.html', {'team_list': team_list})
示例3: EARLPlugin
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
class EARLPlugin(Plugin):
"""
Activate the EARL plugin to generate a report of the test results
using EARL.
"""
name = 'EARL'
def begin(self):
self.graph = Graph()
self.graph.bind("earl", EARL.uri)
def finalize(self, result):
# TODO: add plugin options for specifying where to send
# output.
self.graph.serialize("file:results-%s.rdf" % date_time(), format="pretty-xml")
def addDeprecated(self, test):
print "Deprecated: %s" % test
def addError(self, test, err, capt):
print "Error: %s" % test
def addFailure(self, test, err, capt, tb_info):
print "Failure: %s" % test
def addSkip(self, test):
print "Skip: %s" % test
def addSuccess(self, test, capt):
result = BNode() # TODO: coin URIRef
self.graph.add((result, RDFS.label, Literal(test)))
self.graph.add((result, RDFS.comment, Literal(type(test))))
self.graph.add((result, RDF.type, EARL.TestResult))
self.graph.add((result, EARL.outcome, EARL["pass"]))
示例4: main
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def main(argv):
store = Graph()
for inputFileName in argv:
try:
store.parse(inputFileName)
except Exception:
pass
print store.serialize()
示例5: main
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def main(argv):
# inputFileName1 = '/home/mikel/UPV-EHU/Eclipse_Workspace/MergeRDFGraphs-Galaxy/data/vc-db-3.rdf'
# inputFileName2 = '/home/mikel/UPV-EHU/Eclipse_Workspace/MergeRDFGraphs-Galaxy/data/vc-db-4.rdf'
store = Graph()
for inputFileName in argv:
store.parse(inputFileName)
print store.serialize()
示例6: EARLPlugin
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
class EARLPlugin(Plugin):
"""
Activate the EARL plugin to generate a report of the test results
using EARL.
"""
name = 'EARL'
def begin(self):
self.graph = Graph()
self.graph.bind("earl", EARL.uri)
tool = BNode('rdflib')
self.graph.add((tool, RDF.type, EARL.TestTool))
self.graph.add((tool, RDFS.label, Literal('rdflib.net')))
self.graph.add((tool, RDFS.comment, Literal('nosetests')))
def finalize(self, result):
# TODO: add plugin options for specifying where to send
# output.
self.graph.serialize("file:results-%s.rdf" % \
date_time().replace(':','-'), format="pretty-xml")
def addDeprecated(self, test):
print "Deprecated: %s" % test
def addError(self, test, err, capt):
print "Error: %s" % test
def addFailure(self, test, err, capt, tb_info):
print("FAILED")
result = BNode() # TODO: coin URIRef
self.graph.add((result, RDFS.label, Literal(test)))
self.graph.add((result, RDFS.comment, Literal(type(test))))
self.graph.add((result, RDF.type, EARL.TestResult))
self.graph.add((result, EARL.outcome, EARL["fail"]))
def addSkip(self, test):
print("SKIPPED")
result = BNode() # TODO: coin URIRef
self.graph.add((result, RDFS.label, Literal(test)))
self.graph.add((result, RDFS.comment, Literal(type(test))))
self.graph.add((result, RDF.type, EARL.TestResult))
self.graph.add((result, EARL.outcome, EARL["untested"]))
def addSuccess(self, test, capt):
print("PASSED")
result = BNode() # TODO: coin URIRef
self.graph.add((result, RDFS.label, Literal(test)))
self.graph.add((result, RDFS.comment, Literal(type(test))))
self.graph.add((result, RDF.type, EARL.TestResult))
self.graph.add((result, EARL.outcome, EARL["pass"]))
示例7: agent1
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def agent1():
if request.method == 'GET':
a= g.serialize(format='xml')
return a
else:
message= request.args['content']
gm = Graph()
gm.parse(data=message)
print gm.serialize(format='n3')
a= gjohn.serialize(format='xml')
return a
示例8: makeOtherFormats
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def makeOtherFormats(STs,inputFile):
f=open(inputFile+'/results.nt',"w")
for val in STs:
val0=val[0].replace(" ","_")
val1=val[1].replace(" ","_")
val2=val[2].replace(" ","_")
f.write("<http://"+val0+"> <http://"+val1+"> <http://"+val2+"> .\n")
f.close() #nt created
#----------------------------------------------------------------------------------
#make graph
graph=Graph()
graph.parse(inputFile+'/results.nt',format='nt')
#makin turtle
f=open(inputFile+'/rdf.ttl','w')
s=graph.serialize(format="turtle")
for line in s.split("\n"):
#line=line.replace(" ","")
line=line.replace(" .","\n")
line=line.replace(",",";")
line=line.replace(" "*8,",,")
line=line.replace(" "*4,",")
line=line.replace(" ",",")
print line
# removing prefixes for making evaluation easier
pattern1=r"(ns\d*:)" # Captial Names
match=re.findall(pattern1,line) #symbols
for item in match:
toks=item.split(" ")
newtok=""
line=line.replace(item,newtok)
line=line.replace(";","")
line=line.replace("<http://","")
line=line.replace(">","")
if "@prefix" not in line and len(line)>1:
f.write(line+"\n")
f.close()
#making rdf/xml
f=open(inputFile+'/results.rdf',"w")
s=graph.serialize(format="xml")
for line in s.split("\n"):
f.write(line+"\n")
f.close()
示例9: write_resource
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def write_resource(graph, dataset_uri, out, include_backlinks=True,
format='xml'):
"""
Writes a single dataset
"""
subgraph = Graph()
namespaces.init_bindings(subgraph)
for p, o in graph.predicate_objects(dataset_uri):
subgraph.add((dataset_uri, p, o))
if include_backlinks:
for s, p in graph.subject_predicates(dateset_uri):
subgraph.add((s, p, dataset_uri))
subgraph.serialize(destination=out, format=format)
示例10: test_n3
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def test_n3(self):
g = Graph()
g.add((URIRef("http://example.com/foo"),
URIRef("http://example.com/bar"),
URIRef("http://example.com/baz")))
n3 = g.serialize(format="n3")
self.assertTrue("<http://example.com/foo> ns1:bar <http://example.com/baz> ." in n3)
示例11: request
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def request(self, environ, start_response, method, negotiated):
from rdflib.graph import Graph
from rdflib.term import URIRef
negotiated = list(negotiated)
# we have to invert the autoneg dictionary first to check
# if the request we have ends with one of the file extensions
# that is was asked for directly
extmap = {}
for content_type, extlist in negotiated:
[extmap.setdefault(ext, content_type) for ext in extlist]
# get the graph uri that has been requested
path = self.get_path(environ)
# if it ends with an extension, use that
for ext, content_type in extmap.items():
if path.endswith("." + ext):
path = path[: -len(ext) - 1]
break
content_type = None
# otherwise use the content-negotiation
if content_type is None:
content_type = negotiated[0][0]
# initialise the graph over the store
g = Graph(self.store, identifier=URIRef(path))
# send the serialised graph
start_response("200 OK", [("Content-type", content_type), ("Vary", "Accept")])
yield g.serialize(format=self.serialisations.get(content_type, "pretty-xml"))
示例12: replaceObjectUri
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def replaceObjectUri(graph):
for subj, pred, obj in graph:
tmp_graph = Graph()
# determine obj's cellar id, if it exists (owl:sameAs)
results = graph.triples((None, OWL.sameAs, obj))
sameas_stmnt = None
try:
# owl:sameAs statement with cellar id as subject
sameas_stmnt = next(results)
except StopIteration:
# no owl:sameAs statement found
pass
# nothing to replace
if sameas_stmnt is None:
tmp_graph.add((subj, pred, obj))
# replace obj by cellar_id
else:
cellar_id = sameas_stmnt[0]
# filter reflexive statements
if str(cellar_id) != str(subj) and str(pred) != str(OWL.sameAs):
tmp_graph.add((subj, pred, cellar_id))
# original owl:sameAs statement should be printed once
else:
tmp_graph.add((subj, pred, obj))
print(tmp_graph.serialize(format='nt').decode('ascii').rstrip('\n'))
示例13: convert
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def convert(self):
store = Graph()
store.bind("dc", "http://purl.org/dc/elements/1.1/")
store.bind("data", "http://data.rpi.edu/vocab/")
DC = Namespace("http://purl.org/dc/elements/1.1/")
DATA = Namespace("http://data.rpi.edu/vocab/")
RDFS = Namespace("http://www.w3.org/2000/01/rdf-schema#")
FOAF = Namespace("http://xmlns.com/foaf/0.1/")
header = self.reader.next() #Skip header
minSize = len(header)
#print header
for row in self.reader:
if len(row) != minSize:
print "Number of columns different than header ({0} vs. {1}). Skipping".format(len(row), minSize)
continue
store.add((row[8], DC['identifier'], Literal(row[0])))
names = row[2].split(", ")
creator=URIRef("http://data.rpi.edu/people/"+names[0].capitalize()+names[1].capitalize())
store.add((row[8], DC['creator'], creator))
store.add((creator, FOAF['firstName'], names[0]))
store.add((creator, DC['family_name'], names[1]))
store.add((row[8], DC['dateAccepted'], Literal(row[5])))
store.add((row[8], RDFS['comments'], Literal(row[6])))
store.add((row[8], DC['description'], Literal(row[6])))
store.add((row[8], DC['bibliographicCitation'], Literal(row[7])))
store.add((row[8], DC['title'], Literal(row[10])))
store.add((row[8], RDFS['label'], Literal(row[10])))
store.add((row[8], DC['subject'], URIRef(DATA+re.sub("\s", "_", row[9]))))
print(store.serialize(format="pretty-xml"))
示例14: jsondict2graph
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def jsondict2graph(json_dict):
g = Graph()
[g.bind(*x) for x in ns_store.items()]
for triple in json_dict['results']['bindings']:
ts = triple['s'].get('type',None)
vs = triple['s']['value']
if ts == 'uri':
s = URIRef(vs)
elif ts == 'literal':
s = Literal(vs)
elif ts == 'bnode':
s = BNode(vs)
#logging.debug(s)
p = URIRef(triple['p']['value'])
#logging.debug(p)
to = triple['o'].get('type',None)
vo = triple['o']['value']
dto = triple['o'].get('datatype',None)
if to == 'uri':
o = URIRef(triple['o']['value'])
elif to == 'literal':
o = Literal(triple['o']['value'])
if dto:
o.datatype = URIRef(dto)
elif ts == 'bnode':
o = BNode(vo)
#logging.debug(o)
g.add((s,p,o))
logging.debug(g.serialize(format='turtle'))
return g
示例15: create
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import serialize [as 别名]
def create(self, name, label, description):
'''
Create a new collection and return its URI
@param name: the name of the collection
@param label: a short label
@param description: a longer blob of text describing the collection
'''
# Get the URI for this collection
uri = self.get_uri(name)
logger.debug("Create collection {}".format(uri))
# Create and populate the description of the collection
graph = Graph()
graph.add((URIRef(uri), RDF.type, VOID.Dataset))
graph.add((URIRef(uri), RDFS.label, Literal(label)))
graph.add((URIRef(uri), RDFS.comment, Literal(description)))
data = graph.serialize(format="nt").decode()
# Prepare the query
query = """
INSERT DATA {
__PAYLOAD__
}
""".replace("__PAYLOAD__", data)
sparql = SPARQLWrapper(self.sparul)
sparql.setQuery(query)
sparql.setMethod(POST)
# Execute it
sparql.query()
# Return the uri of the collection
return uri