本文整理汇总了Python中rdflib.ConjunctiveGraph.serialize方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.serialize方法的具体用法?Python ConjunctiveGraph.serialize怎么用?Python ConjunctiveGraph.serialize使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.ConjunctiveGraph
的用法示例。
在下文中一共展示了ConjunctiveGraph.serialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def load(self, url):
src = VOCAB_SOURCE_MAP.get(str(url), url)
if os.path.isfile(url):
context_id = create_input_source(url).getPublicId()
last_vocab_mtime = self.mtime_map.get(url)
vocab_mtime = os.stat(url).st_mtime
if not last_vocab_mtime or last_vocab_mtime < vocab_mtime:
logger.debug("Parse file: '%s'", url)
self.mtime_map[url] = vocab_mtime
# use CG as workaround for json-ld always loading as dataset
graph = ConjunctiveGraph()
graph.parse(src, format=guess_format(src))
self.graph.remove_context(context_id)
for s, p, o in graph:
self.graph.add((s, p, o, context_id))
return graph
else:
context_id = url
if any(self.graph.triples((None, None, None), context=context_id)):
logger.debug("Using context <%s>" % context_id)
return self.graph.get_context(context_id)
cache_path = self.get_fs_path(url)
if os.path.exists(cache_path):
logger.debug("Load local copy of <%s> from '%s'", context_id, cache_path)
return self.graph.parse(cache_path, format='turtle', publicID=context_id)
else:
logger.debug("Fetching <%s> to '%s'", context_id, cache_path)
graph = self.graph.parse(src,
format='rdfa' if url.endswith('html') else None)
with open(cache_path, 'w') as f:
graph.serialize(f, format='turtle')
return graph
示例2: fusion
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def fusion(ontologies, output):
global mode
# Definition of namespaces
# Uncomment if needed
# NS_owl = Namespace("http://www.w3.org/2002/07/owl#")
# NS_rdfs = Namespace("http://www.w3.org/2000/01/rdf-schema#")
# NS_xsd = Namespace("http://www.w3.org/2001/XMLSchema#")
# NS_rdf = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
# NS_mcf = Namespace("http://www.mycorporisfabrica.org/ontology/mcf.owl#")
# Final graph creation
gMerge = ConjunctiveGraph()
myPrint("Beginning additions...\n\n")
for ontology in ontologies:
gAdd = ConjunctiveGraph()
if mode == 2 or mode == 3:
myPrint("\tParsing ontology "+ontology+"...\n")
gAdd.parse(ontology, format=guess_format(ontology))
if mode == 2 or mode == 3:
myPrint("\tAdding ontology "+ontology+", "+str(len(gAdd))+ " triples...\n")
gMerge = gMerge + gAdd
if mode == 2 or mode == 3:
myPrint("\tOntology "+ontology+" added !\n")
myPrint("\tNew size of merged ontology : "+str(len(gMerge))+" triples\n\n")
myPrint("Additions complete !\n")
myPrint("Final size of merged ontology : "+str(len(gMerge))+" triples\n\n")
myPrint("Saving the ontology in turtle format...\n")
# Saving the merged ontology in turtle
gMerge.serialize(output, format="turtle")
myPrint("Saving done !\n\n")
示例3: out
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def out(self,file) :
# RDF output
RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
RDFS = Namespace("http://www.w3.org/2000/01/rdf-schema#")
GT = Namespace("http://purl.org/ontology/flat/")
FOAF = Namespace("http://xmlns.com/foaf/0.1/")
DC = Namespace("http://purl.org/dc/elements/1.1/")
WGS = Namespace("http://www.w3.org/2003/01/geo/wgs84_pos#")
graph = ConjunctiveGraph()
flat = URIRef("#flat")
p = BNode()
e = URIRef(self.email)
i = URIRef(self.image)
graph.add((flat,RDF.type,GT['Flat']))
graph.add((flat,FOAF['based_near'],p))
graph.add((p,RDFS.label,Literal(self.place)))
graph.add((p,DC['title'],Literal(self.location)))
graph.add((p,WGS['lat'],Literal(self.lat)))
graph.add((p,WGS['long'],Literal(self.lng)))
graph.add((flat,FOAF['mbox'],e))
graph.add((flat,FOAF['depiction'],i))
graph.add((flat,DC['title'],Literal(self.title)))
graph.add((flat,DC['description'],Literal(self.description)))
print graph.serialize(destination=file,format='xml')
示例4: get_rdf
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def get_rdf():
rdf = ConjunctiveGraph()
for key in COUNTRIES.keys():
print "parsing %s" % COUNTRIES[key]
rdf.parse(COUNTRIES[key])
print "serialize"
rdf.serialize("countries.rdf")
示例5: add_mediator
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def add_mediator(params):
#Write user metadata and save the rdf file
graph = Graph()
for prefix, url in namespaces.iteritems():
graph.bind(prefix, URIRef(url))
uri = URIRef("http://vocab.ox.ac.uk/owner/uuid:%s"%uuid.uuid4())
graph.add((uri, namespaces['foaf']['firstName'], Literal(params['firstname'])))
graph.add((uri, namespaces['foaf']['lastName'], Literal(params['lastname'])))
graph.add((uri, namespaces['foaf']['mbox'], Literal(params['email'])))
graph.add((uri, namespaces['foaf']['account'], Literal(params['username'])))
if 'title' in params and params['title']:
graph.add((uri, namespaces['foaf']['title'], Literal(params['title'])))
if 'department' in params and params['department']:
department = params['department'].split(';')
for d in department:
graph.add((uri, namespaces['dcterms']['isPartOf'], Literal(d.strip())))
rdf_str = None
rdf_str = graph.serialize()
f = codecs.open(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']), 'w', 'utf-8')
f.write(rdf_str)
f.close()
graph2 = Graph()
graph2.parse(ag.mediatorslist)
for prefix, url in namespaces.iteritems():
graph2.bind(prefix, URIRef(url))
graph2.add((uri, namespaces['foaf']['account'], Literal(params['username'])))
rdf_str = None
rdf_str = graph2.serialize()
f = codecs.open(ag.mediatorslist, 'w', 'utf-8')
f.write(rdf_str)
f.close()
return True
示例6: serialize_demo
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def serialize_demo():
try:
store = ConjunctiveGraph()
store.parse(FILE, format='xml')
print store.serialize(format='xml')
except OSError:
print "Cannot read file '%s'" % FILE
示例7: update
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def update():
"""
Update the library with new articles.
"""
graph = ConjunctiveGraph()
# load the existing graph
library = 'data/articles.rdf'
graph.load(library)
feeds = {
"http://www3.interscience.wiley.com/rss/journal/118485807": "wiley.xsl",
"http://phg.sagepub.com/rss/current.xml": "sage.xsl",
"http://www.informaworld.com/ampp/rss~content=t713446924": "infoworld.xsl",
"http://www.informaworld.com/ampp/rss~content=t788352614": "infoworld.xsl",
"http://www.envplan.com/rss.cgi?journal=D": "envplan.xsl",
"http://www.envplan.com/rss.cgi?journal=A": "envplan.xsl",
"http://cgj.sagepub.com/rss/current.xml": "sage.xsl"
}
for feed, stylesheet in feeds.iteritems():
# grab the feed and transform it
print "grabbing ", feed
new = StringIO.StringIO(feed_transform(feed, stylesheet))
# merge the new triples into the graph
graph.parse(new)
new.close()
graph.serialize(library, format='pretty-xml')
示例8: to_rdf_etree
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def to_rdf_etree(sources):
graph = ConjunctiveGraph()
for source in sources:
graph.load(source, format=guess_format(source))
io = StringIO()
graph.serialize(io, format="pretty-xml")
io.seek(0)
return etree.parse(io)
示例9: get
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def get(self, id, format):
# Content negotiation
if format is None:
accept = self.request.headers.get('Accept').lower()
if "application/rdf+xml" in accept:
self.set_status(303)
self.set_header("Location", self.base_uri + "/signs/" + id + ".rdf")
else:
self.set_status(303)
self.set_header("Location", self.base_uri + "/signs/" + id + ".json")
self.finish()
# invalid format
elif format != ".json" and format != ".rdf":
self.write_error(401, message="Format %s not supported" % format)
self.finish()
# call socrata
else:
crime = yield tornado.gen.Task(SocrataLookup.get_crime, id)
# Connection still good after calling socrata
if not self.request.connection.stream.closed():
if not crime:
self.write_error(404, message="crime not found")
self.finish()
else:
crime = models.Crime(crime, self.base_uri)
# JSON
if format == ".json":
self.set_header("Content-Type", "application/json")
self.write(json.dumps(crime))
# RDF
elif format == ".rdf" or format == ".nt" or format == ".ttl":
graph = ConjunctiveGraph()
graph.bind('geo', GEO)
graph.bind('dcterms', DCTERMS)
graph.bind('dbpediaowl', DBPEDIAOWL)
graph.bind('parksafecrime', PARKSAFECRIME)
crimeURIRef = URIRef(crime['uri'])
graph.add((crimeURIRef, RDF.type, DBPEDIAOWL['event']))
graph.add((crimeURIRef, GEO['lat'], Literal(crime['latitude'])))
graph.add((crimeURIRef, GEO['lon'], Literal(crime['longitude'])))
graph.add((crimeURIRef, PARKSAFECRIME['description'], Literal(crime['description'])))
graph.add((crimeURIRef, PARKSAFECRIME['date'], Literal(crime['date'])))
graph.add((crimeURIRef, PARKSAFECRIME['block'], Literal(crime['block'])))
graph.add((crimeURIRef, PARKSAFECRIME['type'], Literal(crime['type'])))
if format == ".rdf":
self.set_header("Content-Type", "application/rdf+xml")
self.write(graph.serialize())
elif format == ".nt":
self.set_header("Content-Type", "text/plain")
self.write(graph.serialize(format='nt'))
else:
self.set_header("Content-Type", "text/turtle")
self.write(graph.serialize(format='turtle'))
self.finish()
示例10: dump
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def dump(self, f):
assert self.alldata, ".load() not called"
graph = ConjunctiveGraph()
for triple in self.preamble():
graph.add(triple)
for triple in self.classes():
graph.add(triple)
for spell in self.alldata:
for triple in spell:
graph.add(triple)
graph.serialize(destination=f, format='n3')
graph.serialize(destination=sys.stdout, format='n3')
示例11: __init__
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
class Store:
def __init__(self):
self.graph = ConjunctiveGraph()
if os.path.exists(storefn):
self.graph.load(storeuri, format='n3')
self.graph.bind('dc', DC)
self.graph.bind('foaf', FOAF)
self.graph.bind('imdb', IMDB)
self.graph.bind('rev', 'http://purl.org/stuff/rev#')
def save(self):
self.graph.serialize(storeuri, format='n3')
def who(self, who=None):
if who is not None:
name, email = (r_who.match(who).group(1), r_who.match(who).group(2))
self.graph.add((URIRef(storeuri), DC['title'], Literal(title % name)))
self.graph.add((URIRef(storeuri + '#author'), RDF.type, FOAF['Person']))
self.graph.add((URIRef(storeuri + '#author'),
FOAF['name'], Literal(name)))
self.graph.add((URIRef(storeuri + '#author'),
FOAF['mbox'], Literal(email)))
self.save()
else:
return self.graph.objects(URIRef(storeuri + '#author'), FOAF['name'])
def new_movie(self, movie):
movieuri = URIRef('http://www.imdb.com/title/tt%s/' % movie.movieID)
self.graph.add((movieuri, RDF.type, IMDB['Movie']))
self.graph.add((movieuri, DC['title'], Literal(movie['title'])))
self.graph.add((movieuri, IMDB['year'], Literal(int(movie['year']))))
self.save()
def new_review(self, movie, date, rating, comment=None):
review = BNode() # @@ humanize the identifier (something like #rev-$date)
movieuri = URIRef('http://www.imdb.com/title/tt%s/' % movie.movieID)
self.graph.add((movieuri, REV['hasReview'], URIRef('%s#%s' % (storeuri, review))))
self.graph.add((review, RDF.type, REV['Review']))
self.graph.add((review, DC['date'], Literal(date)))
self.graph.add((review, REV['maxRating'], Literal(5)))
self.graph.add((review, REV['minRating'], Literal(0)))
self.graph.add((review, REV['reviewer'], URIRef(storeuri + '#author')))
self.graph.add((review, REV['rating'], Literal(rating)))
if comment is not None:
self.graph.add((review, REV['text'], Literal(comment)))
self.save()
def movie_is_in(self, uri):
return (URIRef(uri), RDF.type, IMDB['Movie']) in self.graph
示例12: Topic
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
class Topic(object):
def __init__(self, entity_name, entity_id):
'''
Constructor
'''
# Get the event page and compute its id
self.entity_id = entity_id
self.resource = LDES[self.entity_id]
# Create the graph
self.graph = ConjunctiveGraph()
self.graph.bind('swc', SWC)
self.graph.bind('cfp', CFP)
self.graph.bind('ical', ICAL)
self.graph.bind('foaf', FOAF)
self.graph.bind('dct', DCT)
self.graph.bind('lode', LODE)
# Declare the type of the resource
self.graph.add((self.resource, RDF.type, SIOCT['Tag']))
self.graph.add((self.named_graph(), DCT['modified'], Literal(datetime.now())))
def get_rdf_data(self):
return self.graph.serialize()
def named_graph(self):
return URIRef(NAMED_GRAPHS_BASE + self.entity_id + '.rdf')
def process(self, record, entity_url):
# Get the document
document = BeautifulSoup(urllib2.urlopen("http://eventseer.net" + entity_url).read())
del document
示例13: ConvertToRDFN3
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def ConvertToRDFN3 (filename, destinationFileName):
_graph = ConjunctiveGraph()
_graph.parse(filename, format="nt")
of = open(destinationFileName, "wb")
of.write(_graph.serialize(format="n3"))
of.close()
示例14: get_rdf_template
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def get_rdf_template(item_uri, item_id):
g = ConjunctiveGraph(identifier=item_uri)
g.bind('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
g.bind('dcterms', 'http://purl.org/dc/terms/')
g.add((URIRef(item_uri), URIRef('http://purl.org/dc/terms/identifier'), Literal(item_id)))
data2 = g.serialize(format='xml', encoding="utf-8") + '\n'
return data2
示例15: change_status
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import serialize [as 别名]
def change_status(vocabprefix, uri, predicate, message, action):
if not action in ['add', 'remove']:
return False
vocab_uri = URIRef(uri)
vocabdir = os.path.join(ag.vocabulariesdir, vocabprefix)
vocabstatusfile = os.path.join(vocabdir, "status.rdf")
if not os.path.isfile(vocabstatusfile):
return False
graph = Graph()
graph.parse(vocabstatusfile)
predicate = predicate.split(':')
ns = predicate[0]
term = predicate[1]
if message and (message.startswith('http://') or message.startswith('file://')):
message = URIRef(message)
elif message:
message = Literal(message)
if action == 'add':
for prefix, url in namespaces.iteritems():
graph.bind(prefix, URIRef(url))
graph.add((vocab_uri, namespaces[ns][term], message))
elif action == 'remove':
graph.remove((vocab_uri, namespaces[ns][term], message))
rdf_str = None
rdf_str = graph.serialize()
f = codecs.open(vocabstatusfile, 'w', 'utf-8')
f.write(rdf_str)
f.close()
return True