本文整理汇总了Python中rdflib.namespace.NamespaceManager类的典型用法代码示例。如果您正苦于以下问题:Python NamespaceManager类的具体用法?Python NamespaceManager怎么用?Python NamespaceManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NamespaceManager类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: load_graph_prefixes
def load_graph_prefixes():
namespace_manager = NamespaceManager(Graph())
# restPrefix = Namespace('http://restaurants.recommender.es/od-data/restaurant/')
# locPrefix = Namespace('http://restaurants.recommender.es/od-data/location/')
# ratePrefix = Namespace('http://restaurants.recommender.es/od-data/rate/')
# contPrefix = Namespace('http://restaurants.recommender.es/od-data/contact/')
#
# namespace_manager.bind('rest', restPrefix)
# namespace_manager.bind('loc', locPrefix)
# namespace_manager.bind('rate', ratePrefix)
# namespace_manager.bind('cont', contPrefix)
tree = ET.parse('metadata.xml')
root = tree.getroot()
prefixes = root.find("prefixes")
for prefix in prefixes:
namespace = Namespace(prefix.find('namespace').text)
prefix_name = prefix.get('name')
namespace_manager.bind(prefix_name, namespace)
return namespace_manager
开发者ID:mgvaldes,项目名称:miri-od-project2016,代码行数:25,代码来源:rdf_graph.py
示例2: canonicalTerm
def canonicalTerm(self, term):
if isinstance(term, URIRef):
if self.prolog is not None:
namespace_manager = NamespaceManager(Graph())
for prefix,uri in self.prolog.prefixBindings.items():
namespace_manager.bind(prefix, uri, override=False)
try:
prefix,uri,localName = namespace_manager.compute_qname(term)
except:
return term
if prefix not in self.prolog.prefixBindings:
return term
else:
return u':'.join([prefix, localName])
else:
return term
elif isinstance(term, Literal):
return term.n3()
elif isinstance(term, BNode):
return term.n3()
else:
assert isinstance(term, Variable)
return term.n3()
开发者ID:RDFLib,项目名称:rdfextras,代码行数:32,代码来源:graph.py
示例3: serialize
def serialize(self, add, delete):
commit = Namespace("urn:commit:" + str(uuid.uuid1()) + ":")
eccrev = Namespace("https://vocab.eccenca.com/revision/")
g = ConjunctiveGraph()
namespace_manager = NamespaceManager(g)
namespace_manager.bind('eccrev', eccrev, override=False)
g.add((commit.term(""), RDF.type, eccrev.Commit))
graphUris = set(delete.keys()) | set(add.keys())
for graphUri in graphUris:
if (graphUri in delete.keys() and len(delete[graphUri]) > 0) or (graphUri in add.keys() and len(add[graphUri]) > 0):
revision = Namespace("urn:revision:" + str(uuid.uuid1()) + ":")
g.add((commit.term(""), eccrev.hasRevision, revision.term("")))
g.add((revision.term(""), RDF.type, eccrev.Revision))
if str(graphUri) != 'http://quitdiff.default/':
g.add((revision.term(""), eccrev.hasRevisionGraph, graphUri))
if graphUri in delete.keys() and len(delete[graphUri]) > 0:
deleteGraphName = revision.term(":delete")
g.add((revision.term(""), eccrev.deltaDelete, deleteGraphName))
for triple in delete[graphUri]:
g.add(triple + (deleteGraphName,))
if graphUri in add.keys() and len(add[graphUri]) > 0:
insertGraphName = revision.term(":insert")
g.add((revision.term(""), eccrev.deltaInsert, insertGraphName))
for triple in add[graphUri]:
g.add(triple + (insertGraphName,))
return g.serialize(format="trig").decode("utf-8")
开发者ID:AKSW,项目名称:QuitDiff,代码行数:32,代码来源:EccrevDiff.py
示例4: serialize_graph
def serialize_graph(request, rdfjson, base):
editgraph = Graph()
editgraph.parse(data=rdfjson, format="rdf-json")
namespace_manager = NamespaceManager(Graph())
for ns in namespaces_dict:
namespace_manager.bind(ns, Namespace(namespaces_dict[ns]), override=False)
editgraph.namespace_manager = namespace_manager
if base:
"""
RDFLib Module to insert the base during serialization is buggy. Manual insertion needed
graphxml_string = editgraph.serialize(format="pretty-xml", base=base)
"""
graphxml_string = editgraph.serialize(format="pretty-xml").decode('utf-8', 'ignore')
graphxml_string = graphxml_string.replace('rdf:RDF\n', 'rdf:RDF\n xml:base="' + base +'"\n')
# print graphxml_string
else:
graphxml_string = editgraph.serialize(format="pretty-xml")
graphxml_to_db = RDF_XML(rdfxml_string = graphxml_string)
graphxml_to_db.save()
print graphxml_to_db.id
return json.dumps({'message':graphxml_to_db.id})
开发者ID:suchmaske,项目名称:rdfedit,代码行数:27,代码来源:ajax.py
示例5: __init__
class NSManager:
def __init__(self, ns_dict):
""" TODO: check ns_dict """
self._ns_dict = ns_dict
self._rdflib_ns_manager = None
def __getitem__(self, key):
return self._ns_dict[key]
def __getattr__(self, key):
try:
return self._ns_dict[key]
except KeyError:
raise AttributeError()
def add_namespace(self, prefix, namespace):
""" TODO: check prefix and namespace """
if self._ns_dict.has_key(prefix):
raise AlreadyRegisteredNSError(prefix)
self._ns_dict[prefix] = namespace
@property
def ns_dict(self):
return self._ns_dict
@property
def rdflib_ns_manager(self):
""" For using prefixes in RDFlib graphs """
if self._rdflib_ns_manager is None:
self._rdflib_ns_manager = NamespaceManager(Graph())
for namesp in self._ns_dict:
self._rdflib_ns_manager.bind(namesp, self._ns_dict[namesp])
return self._rdflib_ns_manager
开发者ID:bcogrel,项目名称:webid-profile,代码行数:34,代码来源:core.py
示例6: __init__
def __init__(self,ruleStore,name = None,
initialWorkingMemory = None,
inferredTarget = None,
nsMap = {},
graphVizOutFile=None,
dontFinalize=False,
goal=None):
self.leanCheck = {}
self.goal = goal
self.nsMap = nsMap
self.name = name and name or BNode()
self.nodes = {}
self.alphaPatternHash = {}
self.ruleSet = set()
for alphaPattern in xcombine(('1','0'),('1','0'),('1','0')):
self.alphaPatternHash[tuple(alphaPattern)] = {}
if inferredTarget is None:
self.inferredFacts = Graph()
namespace_manager = NamespaceManager(self.inferredFacts)
for k,v in nsMap.items():
namespace_manager.bind(k, v)
self.inferredFacts.namespace_manager = namespace_manager
else:
self.inferredFacts = inferredTarget
self.workingMemory = initialWorkingMemory and initialWorkingMemory or set()
self.proofTracers = {}
self.terminalNodes = set()
self.instantiations = {}
start = time.time()
self.ruleStore=ruleStore
self.justifications = {}
self.dischargedBindings = {}
if not dontFinalize:
self.ruleStore._finalize()
self.filteredFacts = Graph()
#'Universal truths' for a rule set are rules where the LHS is empty.
# Rather than automatically adding them to the working set, alpha nodes are 'notified'
# of them, so they can be checked for while performing inter element tests.
self.universalTruths = []
from FuXi.Horn.HornRules import Ruleset
self.rules=set()
self.negRules = set()
for rule in Ruleset(n3Rules=self.ruleStore.rules,nsMapping=self.nsMap):
import warnings
warnings.warn(
"Rules in a network should be built *after* construction via "+
" self.buildNetworkClause(HornFromN3(n3graph)) for instance",
DeprecationWarning,2)
self.buildNetworkFromClause(rule)
self.alphaNodes = [node for node in self.nodes.values() if isinstance(node,AlphaNode)]
self.alphaBuiltInNodes = [node for node in self.nodes.values() if isinstance(node,BuiltInAlphaNode)]
self._setupDefaultRules()
if initialWorkingMemory:
start = time.time()
self.feedFactsToAdd(initialWorkingMemory)
print >>sys.stderr,"Time to calculate closure on working memory: %s m seconds"%((time.time() - start) * 1000)
if graphVizOutFile:
print >>sys.stderr,"Writing out RETE network to ", graphVizOutFile
renderNetwork(self,nsMap=nsMap).write(graphVizOutFile)
开发者ID:carnotip,项目名称:FuXi,代码行数:60,代码来源:Network.py
示例7: init_database
def init_database(self):
""" Open the configured database """
self._init_rdf_graph()
L.debug("opening " + str(self.source))
try:
self.source.open()
except OpenFailError as e:
L.error('Failed to open the data source because: %s', e)
raise
nm = NamespaceManager(self['rdf.graph'])
self['rdf.namespace_manager'] = nm
self['rdf.graph'].namespace_manager = nm
# A runtime version number for the graph should update for all changes
# to the graph
self['rdf.graph.change_counter'] = 0
self['rdf.graph'].store.dispatcher.subscribe(TripleAddedEvent, self._context_changed_handler())
self['rdf.graph'].store.dispatcher.subscribe(TripleRemovedEvent, self._context_changed_handler())
self['rdf.graph']._add = self['rdf.graph'].add
self['rdf.graph']._remove = self['rdf.graph'].remove
self['rdf.graph'].add = self._my_graph_add
self['rdf.graph'].remove = self._my_graph_remove
nm.bind("", self['rdf.namespace'])
开发者ID:openworm,项目名称:PyOpenWorm,代码行数:26,代码来源:data.py
示例8: __init__
def __init__(self, graph):
self.bind = lambda *a: None # disable the bind method
NamespaceManager.__init__(self, graph)
del self.bind # restore original bind method
self.bind("", str(CLD))
self.bind("ma", MA)
self.bind("rdf", RDF)
self.bind("cam", CAM_NS_PREFIX)
开发者ID:oaubert,项目名称:advene2,代码行数:8,代码来源:cinelab_rdf.py
示例9: _create_or_get_graph
def _create_or_get_graph(self,name):
if name not in self.models:
graph = Graph()
namespace_manager = NamespaceManager(Graph())
namespace_manager.bind(DEFAULT_NAMESPACE[0], self.default_ns)
graph.ns_manager = namespace_manager
self.models[name] = graph
return self.models[name]
开发者ID:alexis-jacq,项目名称:minimalkb,代码行数:9,代码来源:rdflib_backend.py
示例10: openDatabase
def openDatabase(self):
""" Open a the configured database """
self._init_rdf_graph()
L.debug("opening " + str(self.source))
self.source.open()
nm = NamespaceManager(self['rdf.graph'])
self['rdf.namespace_manager'] = nm
self['rdf.graph'].namespace_manager = nm
nm.bind("", self['rdf.namespace'])
开发者ID:nheffelman,项目名称:pyopdata,代码行数:10,代码来源:data.py
示例11: initgraphconfig
def initgraphconfig(self, rev):
"""Initialize graph settings.
Public method to initalize graph settings. This method will be run only once.
"""
if self.graphconf is None:
self.graphconf = Graph()
self.nsMngrGraphconf = NamespaceManager(self.graphconf)
self.nsMngrGraphconf.bind('', self.quit, override=False)
graph_files, config_files, rdf_files = self.get_blobs_from_repository(rev)
if len(graph_files) == 0 and len(config_files) == 0:
self.mode = 'graphfiles'
elif len(graph_files) > 0 and len(config_files) > 0:
raise InvalidConfigurationError(
"Conflict. Found graphfiles and QuitStore configuration file.")
elif len(graph_files) > 0:
self.mode = 'graphfiles'
self.__init_graph_conf_with_blobs(graph_files, rev)
elif len(config_files) == 1:
self.mode = 'configuration'
self.__init_graph_conf_from_configuration(config_files[0], rdf_files)
else:
raise InvalidConfigurationError(
"Conflict. Found more than one QuitStore configuration file.")
开发者ID:AKSW,项目名称:QuitStore,代码行数:26,代码来源:conf.py
示例12: __init__
def __init__(self, text=""):
super(Sketch, self).__init__()
self.rdfGraph = rdflib.Graph()
self.namespace_manager = NamespaceManager(self.rdfGraph)
self.SUPPORTED_FORMATS = ['xml', 'n3', 'turtle', 'nt', 'pretty-xml', 'dot']
PREFIXES = [
("", "http://this.sketch#"),
("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
("xml", "http://www.w3.org/XML/1998/namespace"),
("xsd", "http://www.w3.org/2001/XMLSchema#"),
('foaf', "http://xmlns.com/foaf/0.1/"),
("npg", "http://ns.nature.com/terms/"),
("npgg", "http://ns.nature.com/graphs/"),
("npgx", "http://ns.nature.com/extensions/"),
("bibo", "http://purl.org/ontology/bibo/"),
("skos", "http://www.w3.org/2004/02/skos/core#"),
("owl", "http://www.w3.org/2002/07/owl#"),
]
for pref in PREFIXES:
self.bind(pref)
if text:
self.add(text)
开发者ID:MakulaPooja,项目名称:Semantic-Web-Forms,代码行数:26,代码来源:sketch.py
示例13: rdflib_ns_manager
def rdflib_ns_manager(self):
""" For using prefixes in RDFlib graphs """
if self._rdflib_ns_manager is None:
self._rdflib_ns_manager = NamespaceManager(Graph())
for namesp in self._ns_dict:
self._rdflib_ns_manager.bind(namesp, self._ns_dict[namesp])
return self._rdflib_ns_manager
开发者ID:bcogrel,项目名称:webid-profile,代码行数:8,代码来源:core.py
示例14: testExpand
def testExpand(self):
EX = Namespace("http://example.com/")
namespace_manager = NamespaceManager(Graph())
namespace_manager.bind('ex', EX, override=False)
self.testGraph.namespace_manager = namespace_manager
man = Class(EX.Man)
boy = Class(EX.Boy)
woman = Class(EX.Woman)
girl = Class(EX.Girl)
male = Class(EX.Male)
female = Class(EX.Female)
human = Class(EX.Human)
animal = Class(EX.Animal)
cat = Class(EX.Cat)
dog = Class(EX.Dog)
animal = Class(EX.Animal)
animal = cat | dog | human
human += man
human += boy
human += woman
human += girl
male += man
male += boy
female += woman
female += girl
testClass = human & ~ female
self.assertEquals(repr(testClass), 'ex:Human THAT ( NOT ex:Female )')
newtestClass = ComplementExpansion(testClass, debug=True)
self.assertTrue(repr(newtestClass) in [
'( ex:Boy or ex:Man )',
'( ex:Man or ex:Boy )'],
repr(newtestClass))
testClass2 = animal & ~ (male | female)
self.assertEquals(repr(testClass2),
'( ( ex:Cat or ex:Dog or ex:Human ) and ( not ( ex:Male or ex:Female ) ) )')
newtestClass2 = ComplementExpansion(testClass2, debug=True)
testClass2Repr = repr(newtestClass2)
self.assertTrue(testClass2Repr in [
'( ex:Cat or ex:Dog )',
'( ex:Dog or ex:Cat )'],
testClass2Repr)
开发者ID:RDFLib,项目名称:FuXi,代码行数:45,代码来源:__init__.py
示例15: renderNetwork
def renderNetwork(network, nsMap={}):
"""
Takes an instance of a compiled ReteNetwork and a namespace mapping (for constructing QNames
for rule pattern terms) and returns a BGL Digraph instance representing the Rete network
#(from which GraphViz diagrams can be generated)
"""
# from FuXi.Rete import BuiltInAlphaNode
# from BetaNode import LEFT_MEMORY, RIGHT_MEMORY, LEFT_UNLINKING
dot = Dot(graph_type='digraph')
namespace_manager = NamespaceManager(Graph())
for prefix, uri in list(nsMap.items()):
namespace_manager.bind(prefix, uri, override=False)
visitedNodes = {}
edges = []
idx = 0
for node in list(network.nodes.values()):
if node not in visitedNodes:
idx += 1
visitedNodes[node] = generateBGLNode(
dot, node, namespace_manager, str(idx))
dot.add_node(visitedNodes[node])
nodeIdxs = {}
for node in list(network.nodes.values()):
for mem in node.descendentMemory:
if not mem:
continue
bNode = mem.successor
for bNode in node.descendentBetaNodes:
for idx, otherNode in enumerate([bNode.leftNode, bNode.rightNode]):
if node == otherNode and (node, otherNode) not in edges:
for i in [node, bNode]:
if i not in visitedNodes:
idx += 1
nodeIdxs[i] = idx
visitedNodes[i] = generateBGLNode(
dot, i, namespace_manager, str(idx))
dot.add_node(visitedNodes[i])
edge = Edge(visitedNodes[node],
visitedNodes[bNode],
label=idx == 0 and 'left' or 'right')
dot.add_edge(edge)
edges.append((node, bNode))
return dot
开发者ID:drewp,项目名称:FuXi,代码行数:45,代码来源:Util.py
示例16: main
def main(labeled, wid_title_mapping, processed_out, discarded_out, dataset, format,
resource_namespace, fact_namespace, ontology_namespace):
# Namespace prefixes for RDF serialization
RESOURCE_NS = Namespace(resource_namespace)
FACT_EXTRACTION_NS = Namespace(fact_namespace)
ONTOLOGY_NS = Namespace(ontology_namespace)
NAMESPACE_MANAGER = NamespaceManager(Graph())
NAMESPACE_MANAGER.bind('resource', RESOURCE_NS)
NAMESPACE_MANAGER.bind('fact', FACT_EXTRACTION_NS)
NAMESPACE_MANAGER.bind('ontology', ONTOLOGY_NS)
mapping = json.load(wid_title_mapping)
with codecs.open(labeled, 'rb', 'utf8') as f:
labeled = json.load(f)
processed, discarded = to_assertions(labeled, mapping, NAMESPACE_MANAGER, {
'ontology': ONTOLOGY_NS,
'resource': RESOURCE_NS,
'fact_extraction': FACT_EXTRACTION_NS,
}, outfile=dataset, format=format)
with codecs.open(processed_out, 'wb', 'utf8') as f:
f.writelines('\n'.join(processed))
with codecs.open(discarded_out, 'wb', 'utf8') as f:
f.writelines('\n'.join(discarded))
开发者ID:Sergiuu17,项目名称:fact-extractor,代码行数:26,代码来源:labeled_to_assertions.py
示例17: init_database
def init_database(self):
""" Open the configured database """
self._init_rdf_graph()
L.debug("opening " + str(self.source))
self.source.open()
nm = NamespaceManager(self['rdf.graph'])
self['rdf.namespace_manager'] = nm
self['rdf.graph'].namespace_manager = nm
# A runtime version number for the graph should update for all changes
# to the graph
self['rdf.graph.change_counter'] = 0
self['rdf.graph']._add = self['rdf.graph'].add
self['rdf.graph']._remove = self['rdf.graph'].remove
self['rdf.graph'].add = self._my_graph_add
self['rdf.graph'].remove = self._my_graph_remove
nm.bind("", self['rdf.namespace'])
开发者ID:gsarma,项目名称:PyOpenWorm,代码行数:18,代码来源:data.py
示例18: dataset
def dataset(self):
#pdb.set_trace()
if hasattr(self._connection, 'dataset'):
return getattr(self._connection, 'dataset')
if self.store=='Sleepycat':
dataset = Dataset(store=self.store, default_union=True)
dataset.open(self.store_path, create = True)
else:
self.store = Virtuoso(self.connection)
#dataset = Dataset(store=self.store, default_union=True)
dataset = ConjunctiveGraph(store=self.store,identifier=CENDARI)
self.store.connection # force connection
setattr(self._connection, 'dataset', dataset)
nm = NamespaceManager(dataset)
for (prefix, ns) in INIT_NS.iteritems():
nm.bind(prefix, ns)
dataset.namespace_manager = nm
return dataset
开发者ID:CENDARI,项目名称:editorsnotes,代码行数:18,代码来源:semantic.py
示例19: tobj
def tobj(objname):
SCHEMA = Namespace('http://schema.org/')
SPDX = Namespace('http://www.spdx.org/rdf/terms#')
n = NamespaceManager(Graph())
n.bind("schema", SCHEMA)
n.bind("spdx", SPDX)
c = get_db().cursor()
c.execute('SELECT * FROM objects WHERE id=?', (objname,))
obj = c.fetchone()
g = Graph()
g.namespace_manager = n
objuri = URIRef("http://localhost:5000/b/" + obj[0])
robjuri = URIRef("http://localhost:5000/r/" + obj[0])
md5node = BNode()
g.add((md5node, SPDX.checksumValue, Literal(obj[2])))
g.add((md5node, SPDX.algorithm, URIRef("http://packages.qa.debian.org/#checksumAlgorithm_md5sum")))
g.add((objuri, SPDX.checksum, md5node))
g.add((objuri, SCHEMA.fileSize, Literal(obj[1])))
return Response(g.serialize(format="turtle"), mimetype="text/plain")
开发者ID:irl,项目名称:womaas,代码行数:19,代码来源:main.py
示例20: newgraph
def newgraph(request):
print request.method
# Create and bind namespaces
namespace_manager = NamespaceManager(Graph())
for ns in namespaces_dict:
namespace_manager.bind(ns, Namespace(namespaces_dict[ns]))
# Create a new graph
graph = Graph()
graph.namespace_manager = namespace_manager
triple_list = []
subject_list = []
predicate_list = []
subject_set = {}
predicate_set = {}
object_set = {}
# Determine xml:base
subject_base_test_set = {triple[0] for triple in triple_list}
base_set = {subject[:subject.rfind("/")] for subject in subject_base_test_set}
# If all subjects share the same substring-base, this substring-base is likely to be the xml:base.
if len(base_set) == 1:
base = str(list(base_set)[0]) + "/"
else:
base = ""
# Serialize graph
rdfjson = graph.serialize(None, format="rdf-json")
#
triple_fetcher_classes = get_triple_fetcher_classes()
response = render_to_response('rdfedit/triples.html',
{'rdfjson': rdfjson, 'triple_list': triple_list, 'subject_set': subject_set,
'predicate_set': predicate_set, 'object_set': object_set,
'namespaces_dict': json.dumps(namespaces_dict), 'base': base,
'triple_fetcher_classes': triple_fetcher_classes},
context_instance=RequestContext(request))
return response
开发者ID:suchmaske,项目名称:rdfedit,代码行数:43,代码来源:views.py
注:本文中的rdflib.namespace.NamespaceManager类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论