本文整理汇总了Python中rdflib.graph.ConjunctiveGraph.bind方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.bind方法的具体用法?Python ConjunctiveGraph.bind怎么用?Python ConjunctiveGraph.bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.graph.ConjunctiveGraph
的用法示例。
在下文中一共展示了ConjunctiveGraph.bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_issue_250
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def test_issue_250(self):
"""
https://github.com/RDFLib/rdflib/issues/250
When I have a ConjunctiveGraph with the default namespace set,
for example
import rdflib
g = rdflib.ConjunctiveGraph()
g.bind(None, "http://defaultnamespace")
then the Trix serializer binds the default namespace twice in its XML
output, once for the Trix namespace and once for the namespace I used:
print(g.serialize(format='trix').decode('UTF-8'))
<?xml version="1.0" encoding="utf-8"?>
<TriX
xmlns:xml="http://www.w3.org/XML/1998/namespace"
xmlns="http://defaultnamespace"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns="http://www.w3.org/2004/03/trix/trix-1/"
/>
"""
graph = ConjunctiveGraph()
graph.bind(None, "http://defaultnamespace")
sg = graph.serialize(format='trix').decode('UTF-8')
self.assertTrue(
'xmlns="http://defaultnamespace"' not in sg, sg)
self.assertTrue(
'xmlns="http://www.w3.org/2004/03/trix/trix-1/' in sg, sg)
示例2: create_ontology
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def create_ontology(self,tr,predicate,subClass,address,booktitle):
LDT= Namespace("http://www.JceFinalProjectOntology.com/")
ut=Namespace("http://www.JceFinalProjectOntology.com/subject/#")
usubClass=URIRef("http://www.JceFinalProjectOntology.com/subject/"+subClass.strip()+'#')
#LDT.subClass=LDT[subClass]
print(ut)
print(usubClass)
store=IOMemory()
sty=LDT[predicate]
g = rdflib.Graph(store=store,identifier=LDT)
t = ConjunctiveGraph(store=store,identifier=ut)
print ('Triples in graph before add: ', len(t))
#g.add((LDT,RDF.type,RDFS.Class))
g.add((URIRef(LDT),RDF.type,RDFS.Class))
g.add((URIRef(LDT),RDFS.label,Literal("JFPO")))
g.add((URIRef(LDT),RDFS.comment,Literal('class of all properties')))
for v in self.symbols.values():
if self.if_compoTerm(v)==True:
vs=self.splitTerms(v)[0]
else:
vs =v
g.add((LDT[vs],RDF.type,RDF.Property))
g.add((LDT[vs],RDFS.label,Literal('has'+vs)))
g.add((LDT[vs],RDFS.comment,Literal(v)))
g.add((LDT[vs],RDFS.range,OWL.Class))
g.add((LDT[vs],RDFS.domain,Literal(vs)))
g.bind('JFPO',LDT)
#g.commit()
g.serialize('trtst.rdf',format='turtle')
t.add( (ut[tr], RDF.type,OWL.Class) )
t.add((ut[tr],RDFS.subClassOf,OWL.Thing))
t.add((ut[tr],RDFS.label,Literal(tr)))
t.add((ut[tr],DC.title,Literal(booktitle)))
t.add((ut[tr],DC.source,Literal(address)))
t.add((ut[tr],DC[predicate],URIRef(usubClass)))
t.add((ut[tr],LDT[predicate],RDF.Property))
t.add((ut[tr],DC[predicate],URIRef(usubClass)))
t.add((ut[tr],DC[predicate],URIRef(usubClass)))
relation='has'+predicate
t.add((ut[tr],LDT.term(predicate),URIRef(usubClass)))
t.add( (usubClass,RDF.type,OWL.Class))
t.add((usubClass,RDFS.subClassOf,OWL.Thing))
t.add((usubClass,RDFS.subClassOf,URIRef(sty)))
t.add((usubClass,RDFS.label,Literal(subClass)))
#tc=Graph(store=store,identifier=usubClass)
t.bind("dc", "http://http://purl.org/dc/elements/1.1/")
t.bind('JFPO',LDT)
t.commit()
#print(t.serialize(format='pretty-xml'))
t.serialize('test2.owl',format='turtle')
示例3: SiocWiki
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
class SiocWiki(object):
def __init__(self, uri, title=None, created=None):
self.graph = Graph()
self.graph.bind('sioc', SIOC)
self.graph.bind('dc', DC)
self.graph.bind('dcterms', DCTERMS)
self.graph.bind('rdf', RDF)
self._add_site(uri, title)
def _add_site(self, uri, title):
node = URIRef(uri)
self.graph.add((node, RDF.type, SIOC['Site']))
self.graph.add((node, DC['title'], Literal(title)))
return node
def add_page(self, content, title, uri, updated):
node = URIRef(uri)
self.graph.add((node, RDF.type, SIOC['Wiki']))
self.graph.add((node, SIOC['link'], URIRef(uri)))
self.graph.add((node, DC['title'], Literal(title)))
self.graph.add((node, DC['content'], Literal(content)))
self.graph.add((node, DCTERMS['updated'], Literal(updated)))
def to_str(self):
return self.graph.serialize(format="pretty-xml")
示例4: build_graph
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def build_graph(self):
graph = ConjunctiveGraph()
graph.bind('sioc', SIOC)
graph.bind('foaf', FOAF)
graph.bind('rdfs', RDFS)
graph.bind('dct', DCT)
graph.bind('mvcb', MVCB)
swaml = URIRef("http://swaml.berlios.de/doap#swaml")
doc = URIRef(self.base)
graph.add((doc, RDF.type, FOAF["Document"]))
graph.add((doc, RDFS.label, Literal("RDF version of the message '%s' retrieved from MarkMail API" % self.key))) #FIXME: this should go out of this api
graph.add((doc, MVCB.generatorAgent, swaml))
message = URIRef(self.get_uri())
graph.add((message, RDF.type, SIOC.Post))
graph.add((message, RDF.type, SIOCT.MailMessage))
graph.add((doc, FOAF.primaryTopic, message))
graph.add((message, SIOC.id, Literal(self.key)))
graph.add((message, SIOC.link, URIRef("http://markmail.org/message/%s" % self.key)))
#graph.add((message, SIOC.has_container,URIRef(self.config.get('base')+'forum')))
#graph.add((message, SIOC.has_creator, URIRef(self.getSender().getUri())))
graph.add((message, DCT.title, Literal(self.title)))
#graph.add((message, DCT.created, Literal(self.getDate(), datatype=XSD[u'dateTime'])))
graph.add((message, SIOC.content, Literal(self.content)))
self.set_graph(graph)
示例5: serialize
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def serialize(self, stream=None, rdf_format='trig', **kwargs):
"""
Serializes a :class:`~prov.model.ProvDocument` instance to
`Prov-O <https://www.w3.org/TR/prov-o/>`_.
:param stream: Where to save the output.
"""
container = self.encode_document(self.document)
newargs = kwargs.copy()
newargs['format'] = rdf_format
if newargs['format'] == 'trig':
gr = ConjunctiveGraph()
gr.context_aware = True
gr.parse(data=container.serialize(format='nquads'), format='nquads')
for namespace in container.namespaces():
if namespace not in list(gr.namespaces()):
gr.bind(namespace[0], namespace[1])
container = gr
if six.PY2:
buf = io.BytesIO()
try:
container.serialize(buf, **newargs)
buf.seek(0, 0)
# Right now this is a bytestream. If the object to stream to is
# a text object is must be decoded. We assume utf-8 here which
# should be fine for almost every case.
if isinstance(stream, io.TextIOBase):
stream.write(buf.read().decode('utf-8'))
else:
stream.write(buf.read())
finally:
buf.close()
else:
buf = io.BytesIO()
try:
container.serialize(buf, **newargs)
buf.seek(0, 0)
# Right now this is a bytestream. If the object to stream to is
# a text object is must be decoded. We assume utf-8 here which
# should be fine for almost every case.
if isinstance(stream, io.TextIOBase):
stream.write(buf.read().decode('utf-8'))
else:
stream.write(buf.read()) #.encode('utf-8'))
finally:
buf.close()
示例6: rdf_description
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def rdf_description(name, notation='xml' ):
"""
Funtion takes title of node, and rdf notation.
"""
valid_formats = ["xml", "n3", "ntriples", "trix"]
default_graph_uri = "http://gstudio.gnowledge.org/rdfstore"
configString = "/var/tmp/rdfstore"
# Get the Sleepycat plugin.
store = plugin.get('Sleepycat', Store)('rdfstore')
# Open previously created store, or create it if it doesn't exist yet
graph = Graph(store="Sleepycat",
identifier = URIRef(default_graph_uri))
path = mkdtemp()
rt = graph.open(path, create=False)
if rt == NO_STORE:
#There is no underlying Sleepycat infrastructure, create it
graph.open(path, create=True)
else:
assert rt == VALID_STORE, "The underlying store is corrupt"
# Now we'll add some triples to the graph & commit the changes
rdflib = Namespace('http://sbox.gnowledge.org/gstudio/')
graph.bind("gstudio", "http://gnowledge.org/")
exclusion_fields = ["id", "rght", "node_ptr_id", "image", "lft", "_state", "_altnames_cache", "_tags_cache", "nid_ptr_id", "_mptt_cached_fields"]
node=Objecttype.objects.get(title=name)
node_dict=node.__dict__
subject=str(node_dict['id'])
for key in node_dict:
if key not in exclusion_fields:
predicate=str(key)
pobject=str(node_dict[predicate])
graph.add((rdflib[subject], rdflib[predicate], Literal(pobject)))
graph.commit()
print graph.serialize(format=notation)
graph.close()
示例7: parse
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def parse(self, source, graph):
# we're currently being handed a Graph, not a ConjunctiveGraph
assert graph.store.context_aware # is this implied by formula_aware
assert graph.store.formula_aware
conj_graph = ConjunctiveGraph(store=graph.store)
conj_graph.default_context = graph # TODO: CG __init__ should have a default_context arg
# TODO: update N3Processor so that it can use conj_graph as the sink
conj_graph.namespace_manager = graph.namespace_manager
sink = Sink(conj_graph)
if False:
sink.quantify = lambda *args: True
sink.flatten = lambda *args: True
baseURI = graph.absolutize(source.getPublicId() or source.getSystemId() or "")
p = N3Processor("nowhere", sink, baseURI=baseURI) # pass in "nowhere" so we can set data instead
p.userkeys = True # bah
p.data = source.getByteStream().read() # TODO getCharacterStream?
p.parse()
for prefix, namespace in p.bindings.items():
conj_graph.bind(prefix, namespace)
示例8: gnis2rdf
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def gnis2rdf(gnisfilename, rdffilename):
gnisfile = open(gnisfilename, 'rb')
store = ConjunctiveGraph(identifier='temp')
if not gnisfile:
print('Error opening gnis file!')
return False
gnisreader = csv.reader(gnisfile, delimiter='|')
# Drop first row
gnisreader.next()
for r in gnisreader:
InsertGNISFeature(r, store)
# Add prefixes to store
store.bind('gnis', gnis)
store.bind('geo', geo)
print('Serializing rdf...')
store.serialize(destination=rdffilename, format='n3')
print('created ' + str(len(store)) + ' triples')
示例9: gnis2rdf
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def gnis2rdf(gnisfilename, rdffilename):
gnisfile = open(gnisfilename, "rb")
store = ConjunctiveGraph(identifier="temp")
if not gnisfile:
print("Error opening gnis file!")
return False
gnisreader = csv.reader(gnisfile, delimiter="|")
# Drop first row
gnisreader.next()
for r in gnisreader:
InsertGNISFeature(r, store)
# Add prefixes to store
store.bind("gnis", gnis)
store.bind("geo", geo)
print("Serializing rdf...")
store.serialize(destination=rdffilename, format="n3")
print("created " + str(len(store)) + " triples")
示例10: gatherAndExportUserData
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def gatherAndExportUserData(repo_name,userId,userToken):
store = IOMemory()
g=ConjunctiveGraph(store=store)
g.bind("av",ns)
g.bind("sc",sc)
g.bind("dbo",dbo)
g.bind("fb",fb)
createGraphForFBUser(store,repo_name,userId,userToken)
graphString = g.serialize(format="n3")
with open("user.ttl","w") as f:
f.write(graphString)
response = sesame.import_content(repo_name,graphString)
示例11: gatherAndExportGenreData
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def gatherAndExportGenreData(repo_name):
store = IOMemory()
g=ConjunctiveGraph(store=store)
g.bind("av",ns)
g.bind("sc",sc)
g.bind("dbo",dbo)
g.bind("fb",fb)
genreRelations = dbpedia.getDBpediaGenreRelations()
genreNames = dbpedia.getDbpediaMusicGenres()
createGraphForGenres(store,genreNames,genreRelations)
graphString = g.serialize(format="n3")
with open("genres.ttl","w") as f:
f.write(graphString)
response = sesame.import_content(repo_name,graphString)
示例12: gatherAndExportGlobalData
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def gatherAndExportGlobalData(repo_name):
store = IOMemory()
g=ConjunctiveGraph(store=store)
g.bind("av",ns)
g.bind("sc",sc)
g.bind("dbo",dbo)
g.bind("fb",fb)
venues = importVenuesFromFile("fb_data_stuff/venues.txt")
events = importEventsFromDirectory("fb_data_stuff/events/")
createGraphForEvents(store,repo_name,events)
createGraphForVenues(store,venues)
createGraphForEventArtistsAndGenres(store,repo_name,events)
graphString = g.serialize(format="n3")
with open("global.ttl","w") as f:
f.write(graphString)
示例13: generaterdf
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
def generaterdf(outputfile, groupName):
# find the groups based on the name of the group.
myList = groupSearch(httpurl,groupName)
# take the first group's id
groupId = myList['results'][0]['id']
print groupId
# Find all items in one group.
myList = groupContent(httpurl,groupId)
# REsult
print "total records : %s" % myList['total']
print "start record : %s" % myList['start']
print "num record : %s" % myList['num']
print "next start record : %s" % myList['nextStart']
#
# The following fields are returned.
#itemType, culture, owner, guid, screenshots, id, size, appCategories, access, avgRating, title, numRatings, numComments, snippet,
#listed, largeThumbnail, type, thumbnail, uploaded, industries, description, tags, typeKeywords, extent, banner, properties, name,
#licenseInfo, languages, url, lastModified, documentation, modified, spatialReference, item, numViews, accessInformation
graph = Graph()
store = IOMemory()
dmNs = Namespace('http://' + httpurl + "/rdfschema.rdf#")
dctNs = Namespace("http://purl.org/dc/terms/")
rdfsNs = Namespace("http://www.w3.org/2000/01/rdf-schema#")
g = ConjunctiveGraph(store=store)
g.bind("dm", dmNs)
g.bind("dct", dctNs)
g.bind("rdfs", rdfsNs)
for obj in myList['results']:
print obj['title'] + ' -> ' + obj['id']
subject = URIRef(
'http://' + httpurl + '/home/item.html?id=' + obj['id']
)
tmpgraph = Graph(store=store, identifier=subject)
tmpgraph.add((subject, dctNs['id'], Literal(obj['id'])))
tmpgraph.add((subject, rdfsNs['label'], Literal(obj['title'])))
tmpgraph.add((subject, dmNs['type'], Literal(obj['itemType'])))
if 'url' in obj and obj['url']:
tmpgraph.add((subject, dmNs['serviceURL'], URIRef(obj['url'])))
if 'description' in obj and obj['description']:
description = ' '.join(striphtml(obj['description']).split())
description = re.sub(u"(\u2018|\u2019)", "'", description)
tmpgraph.add((subject, dctNs['description'], Literal(description)))
if obj.get("uploaded","") != "":
# remove timezone from timestamp
timestamp = int(str(obj['uploaded'])[:-3])
date = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d')
tmpgraph.add((subject, dctNs['created'], Literal(date)))
tmpgraph.add((subject, dctNs['issued'], Literal(date)))
if obj.get("title","") != "":
tmpgraph.add((subject, dctNs['title'], Literal(obj['title'])))
if obj.get("owner","") != "":
tmpgraph.add((subject, dctNs['creator'], Literal(obj['owner'])))
if obj.get("tags","") != "":
for keyword in obj['tags']:
tmpgraph.add((subject, dctNs['subject'], Literal(keyword.strip())))
#also "Comments", "Subject", "Category", "Credits"
outRDF = os.path.join(outputfile)
RDFFile = open(outRDF,"w")
RDFFile.writelines(g.serialize())
RDFFile.close()
示例14: Namespace
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
pass
if __name__ == "__main__":
ns = Namespace("http://love.com#")
mary = URIRef("http://love.com/lovers/mary#")
john = URIRef("http://love.com/lovers/john#")
cmary=URIRef("http://love.com/lovers/mary#")
cjohn=URIRef("http://love.com/lovers/john#")
store = IOMemory()
g = ConjunctiveGraph(store=store)
g.bind("loves",ns)
gmary = Graph(store=store, identifier=cmary)
gmary.add((mary, ns['hasName'], Literal("Mary")))
gmary.add((mary, ns['loves'], john))
gjohn = Graph(store=store, identifier=cjohn)
gjohn.add((john, ns['hasName'], Literal("John")))
p1=Process(target=webservices)
p2=Process(target=mainloop)
p1.start()
p2.start()
示例15: init
# 需要导入模块: from rdflib.graph import ConjunctiveGraph [as 别名]
# 或者: from rdflib.graph.ConjunctiveGraph import bind [as 别名]
:Woman = foo:FemaleAdult .
:Title a rdf:Property; = dc:title .
""" # --- End of primer code
# To make this go easier to spit back out...
# technically, we already created a namespace
# with the object init (and it added some namespaces as well)
# By default, your main namespace is the URI of your
# current working directory, so lets make that simpler:
myNS = Namespace(URIRef('http://www.w3.org/2000/10/swap/Primer#'))
primer.bind('', myNS)
primer.bind('owl', 'http://www.w3.org/2002/07/owl#')
primer.bind('dc', 'http://purl.org/dc/elements/1.1/')
primer.bind('swap', 'http://www.w3.org/2000/10/swap/')
sourceCode = StringInputSource(mySource, myNS)
# Lets load it up!
primer.parse(sourceCode, format='n3')
# Now you can query, either directly straight into a list:
[(x, y, z) for x, y, z in primer]
# or spit it back out (mostly) the way we created it: