本文整理汇总了Python中rdflib.graph.Graph.namespaces方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.namespaces方法的具体用法?Python Graph.namespaces怎么用?Python Graph.namespaces使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.graph.Graph
的用法示例。
在下文中一共展示了Graph.namespaces方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testBindingNamespaces
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
def testBindingNamespaces(self):
"""
Binding custom namespaces just works.
"""
g = Graph(store=self.store)
ns = ("prefix", URIRef("http://example.com/prefix"))
self.assertNotIn(ns, list(g.namespaces()))
g.bind(ns[0], ns[1])
self.assertIn(ns, list(g.namespaces()))
示例2: testCannotUpdateDefaultNamespaces
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
def testCannotUpdateDefaultNamespaces(self):
"""
Binding the prefix OR the URI of a default namespaces is a no-op.
"""
g = Graph(store=self.store)
self.assertIn(XML_NAMESPACE, list(g.namespaces()))
g.bind("hello-world", XML_NAMESPACE[1])
self.assertIn(XML_NAMESPACE, list(g.namespaces()))
g.bind(XML_NAMESPACE, URIRef("http://example.com/xml"))
self.assertIn(XML_NAMESPACE, list(g.namespaces()))
示例3: testDefaultNamespaces
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
def testDefaultNamespaces(self):
"""
Test the presence of the default namespaces.
"""
g = Graph(store=self.store)
namespaces = list(g.namespaces())
self.assertIn(XML_NAMESPACE, namespaces)
self.assertIn(RDF_NAMESPACE, namespaces)
self.assertIn(RDFS_NAMESPACE, namespaces)
# and again; by default, initializing the graph will re-bind the namespaces
# using a naive implementation, this will fail.
g = Graph(store=self.store)
g_namespaces = list(g.namespaces())
self.assertIn(XML_NAMESPACE, g_namespaces)
self.assertIn(RDF_NAMESPACE, g_namespaces)
self.assertIn(RDFS_NAMESPACE, g_namespaces)
示例4: TestSPARQLStoreGraphCore
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
class TestSPARQLStoreGraphCore(unittest.TestCase):
store_name = 'SPARQLStore'
path = "http://dbpedia.org/sparql"
storetest = True
create = False
def setUp(self):
self.graph = Graph(store="SPARQLStore")
self.graph.open(self.path, create=self.create)
ns = list(self.graph.namespaces())
assert len(ns) > 0, ns
def tearDown(self):
self.graph.close()
示例5: get_current_version
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
def get_current_version(self):
""" Get Virtuoso Database Graph Current Version """
query = """\
prefix owl: <http://www.w3.org/2002/07/owl#>
prefix xsd: <http://www.w3.org/2001/XMLSchema#>
select distinct ?version ?origen
FROM <%(m_graph)s>
{{
select distinct ?version ?origen ?data
FROM <%(m_graph)s>
where {?s owl:versionInfo ?version;
<%(m_graph)scommited> ?data;
<%(m_graph)sproduto> "%(v_graph)s";
<%(m_graph)sorigen> ?origen.}
ORDER BY desc(?data) LIMIT 1
}}""" % {'m_graph': self.migration_graph, 'v_graph': self.__virtuoso_graph}
graph = Graph(store="SPARQLStore")
graph.open(self.__virtuoso_endpoint, create=False)
graph.store.baseURI = self.__virtuoso_endpoint
ns = list(graph.namespaces())
assert len(ns) > 0, ns
res = graph.query(query)
graph.close()
nroResults = len(res)
if nroResults > 0:
res.vars = ['version', 'origen']
versao, origem = iter(res).next()
versao = None if str(versao) == 'None' else str(versao)
return versao, str(origem)
else:
return None, None
示例6: _load_rules
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
def _load_rules(self, rules_file_name):
# Rules are stored in hash map
rules = {}
# Load the rule base into memory
logger.debug('Loading {}'.format(rules_file_name))
g = Graph().parse(rules_file_name, format="turtle")
# Extract the namespaces from the rule base
r_ns = {}
for (ns, uri) in g.namespaces():
r_ns[ns] = uri
# Compose and prepare the SPARQL queries
for s in g.subjects(RDF.type, INDEXER.Rule):
# Extract the components of the rule
r_if = g.value(s, INDEXER['if']).toPython().replace('\t', '')
r_then = g.value(s, INDEXER['then']).toPython().replace('\t', '')
rule = 'CONSTRUCT {' + r_then + '} WHERE {' + r_if + '}'
# Pre-load the rule
rules[s.toPython()] = prepareQuery(rule, initNs=r_ns)
return rules
示例7: RIFCoreParser
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
class RIFCoreParser(object):
def __init__(self, location=None, graph=None, debug=False):
self.location = location
self.rules = {}
if graph:
assert location is None, "Must supply one of graph or location"
self.graph = graph
if debug:
_debug("RIF in RDF graph was provided")
else:
assert graph is None, "Must supply one of graph or location"
if debug:
_debug("RIF document URL provided %s" % location)
if self.location.find('http:') + 1:
req = urllib2.Request(self.location)
#From:
#http://www.diveintopython.org/http_web_services/redirects.html
# points an 'opener' to the address to 'sniff' out final
# Location header
opener = urllib2.build_opener(SmartRedirectHandler())
f = opener.open(req)
self.content = f.read()
else:
self.content = urllib2.urlopen(self.location).read()
# self.content = open(self.location).read()
try:
transform = etree.XSLT(etree.parse(TRANSFORM_URI))
self.graph = Graph().parse(
data=etree.tostring(
transform(etree.fromstring(self.content))))
if debug:
_debug("Extracted rules from RIF XML format")
except ValueError:
try:
self.graph = Graph().parse(data=self.content, format='xml')
except:
self.graph = Graph().parse(data=self.content, format='n3')
if debug:
_debug("Extracted rules from RIF in RDF document")
def getRuleset(self):
"""
>>> parser = RIFCoreParser('http://www.w3.org/2005/rules/test/repository/tc/Frames/Frames-premise.rif')
>>> for rule in parser.getRuleset(): print(rule)
Forall ?Customer ( ns1:discount(?Customer 10) :- ns1:status(?Customer "gold"^^<http://www.w3.org/2001/XMLSchema#string>) )
Forall ?Customer ( ns1:discount(?Customer 5) :- ns1:status(?Customer "silver"^^<http://www.w3.org/2001/XMLSchema#string>) )
>>> parser = RIFCoreParser('http://www.w3.org/2005/rules/test/repository/tc/Guards_and_subtypes/Guards_and_subtypes-premise.rif')
>>> for rule in parser.getRuleset(): print(rule)
"""
self.implications = dict([(impl, (body, bodyType, head, headType))
for impl, body, bodyType, head, headType in
self.graph.query(IMPLIES_PARTS, initNs=rif_namespaces)])
self.rules = dict([(rule, (vars, impl))
for rule, vars, impl
in self.graph.query(RULE_PARTS,
initNs=rif_namespaces)])
self.frames = dict([(frame, (obj, slots))
for frame, obj, slots in self.graph.query(FRAME_PARTS,
initNs=rif_namespaces)])
self.atoms = dict([(atom, (args, op))
for atom, args, op in self.graph.query(
ATOM_PARTS,
initNs=rif_namespaces)])
self.externals = dict([(external, (args, op))
for external, args, op in self.graph.query(
EXTERNAL_PARTS,
initNs=rif_namespaces)])
rt = []
for sentenceCollection in self.graph.objects(predicate=RIF_NS.sentences):
col = Collection(self.graph, sentenceCollection)
for sentence in col:
if RIF_NS.Implies in self.graph.objects(sentence, RDF.type):
rt.append(self.extractImp(sentence))
elif RIF_NS.Forall in self.graph.objects(sentence, RDF.type):
rt.append(self.extractRule(sentence))
return rt
def extractImp(self, impl):
body, bodyType, head, headType = self.implications[impl]
head = first(self.extractPredication(head, headType))
if bodyType == RIF_NS.And:
raise
else:
body = self.extractPredication(body, bodyType)
body = And([first(body)]) if len(body) == 1 else And(body)
return Rule(Clause(body, head), declare=[])
def extractRule(self, rule):
vars, impl = self.rules[rule]
body, bodyType, head, headType = self.implications[impl]
allVars = map(self.extractTerm, Collection(self.graph, vars))
head = first(self.extractPredication(head, headType))
if bodyType == RIF_NS.And:
body = [first(self.extractPredication(
i,
first(self.graph.objects(i, RDF.type)))
#.........这里部分代码省略.........
示例8: main
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
#.........这里部分代码省略.........
nsBinds.update(rs.nsMapping)
elif options.ruleFormat == 'rif':
try:
from FuXi.Horn.RIFCore import RIFCoreParser
rif_parser = RIFCoreParser(location=fileN, debug=options.debug)
rs = rif_parser.getRuleset()
except ImportError:
raise Exception(
"Missing 3rd party libraries for RIF processing"
)
else:
rs = HornFromN3(fileN)
nsBinds.update(rs.nsMapping)
ruleSet.formulae.extend(rs)
#ruleGraph.parse(fileN,format='n3')
ruleSet.nsMapping = nsBinds
for prefix, uri in list(nsBinds.items()):
namespace_manager.bind(prefix, uri, override=False)
closureDeltaGraph = Graph()
closureDeltaGraph.namespace_manager = namespace_manager
factGraph.namespace_manager = namespace_manager
if not options.sparqlEndpoint:
for fileN in facts:
factGraph.parse(fileN, format=options.inputFormat)
if options.imports:
for owlImport in factGraph.objects(predicate=OWL_NS.imports):
factGraph.parse(owlImport)
print("Parsed Semantic Web Graph.. %s" % owlImport)
if not options.sparqlEndpoint and facts:
for pref, uri in factGraph.namespaces():
nsBinds[pref]=uri
if options.stdin:
assert not options.sparqlEndpoint, "Cannot use --stdin with --sparqlEndpoint"
factGraph.parse(sys.stdin, format=options.inputFormat)
#Normalize namespace mappings
#prune redundant, rdflib-allocated namespace prefix mappings
newNsMgr = NamespaceManager(factGraph)
from FuXi.Rete.Util import CollapseDictionary
for k, v in list(CollapseDictionary(dict([(k, v)
for k, v in factGraph.namespaces()])).items()):
newNsMgr.bind(k, v)
factGraph.namespace_manager = newNsMgr
if options.normalForm:
NormalFormReduction(factGraph)
if not options.sparqlEndpoint:
workingMemory = generateTokenSet(factGraph)
if options.builtins:
import imp
userFuncs = imp.load_source('builtins', options.builtins)
rule_store, rule_graph, network = SetupRuleStore(
makeNetwork=True,
additionalBuiltins=userFuncs.ADDITIONAL_FILTERS)
else:
rule_store, rule_graph, network = SetupRuleStore(makeNetwork=True)
network.inferredFacts = closureDeltaGraph
network.nsMap = nsBinds
if options.dlp:
示例9: testOwl
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
def testOwl(self):
options = defaultOptions()
options.debug = True
global REASONING_STRATEGY, GROUND_QUERY, SINGLE_TEST, DEBUG
SINGLE_TEST = options.singleTest
DEBUG = options.debug
GROUND_QUERY = options.groundQuery
REASONING_STRATEGY = options.strategy
testData = {}
here = os.getcwd()
if not here.endswith('/test') and not here.endswith('entailment'):
os.chdir(here + '/test')
for manifest in glob('OWL/*/Manifest*.rdf'):
if manifest in Tests2Skip:
continue
if (REASONING_STRATEGY is not None and manifest in NonNaiveSkip) or\
(REASONING_STRATEGY == 'sld' and manifest in TopDownTests2Skip) or \
(REASONING_STRATEGY == 'bfp' and manifest in BFPTests2SKip) or\
(REASONING_STRATEGY == 'gms' and manifest in MagicTest2Skip):
continue
skip = False
for pattern2Skip in patterns2Skip:
if manifest.find(pattern2Skip) > -1:
skip = True
break
if skip:
continue
manifestStore = plugin.get(RDFLIB_STORE,Store)()
manifestGraph = Graph(manifestStore)
manifestGraph.parse(open(manifest))
rt = manifestGraph.query(MANIFEST_QUERY,
initNs=nsMap,
DEBUG=False)
# print(list(manifestGraph.namespace_manager.namespaces()))
for status,premise,conclusion, feature, description in rt:
if feature in Features2Skip:
continue
premise = manifestGraph.namespace_manager.compute_qname(premise)[-1]
conclusion = manifestGraph.namespace_manager.compute_qname(conclusion)[-1]
premiseFile = '/'.join(manifest.split('/')[:2] + [premise])
conclusionFile = '/'.join(manifest.split('/')[:2] + [conclusion])
print(premiseFile)
print(conclusionFile)
if status == 'APPROVED':
if SINGLE_TEST and premiseFile != SINGLE_TEST:
continue
assert os.path.exists('.'.join([premiseFile,'rdf']))
assert os.path.exists('.'.join([conclusionFile,'rdf']))
print("<%s> :- <%s>" % ('.'.join([conclusionFile,'rdf']),
'.'.join([premiseFile,'rdf'])))
store = plugin.get(RDFLIB_STORE,Store)()
store.open(RDFLIB_CONNECTION)
factGraph = Graph(store)
factGraph.parse(open('.'.join([premiseFile,'rdf'])))
nsMap.update(dict([(k,v)
for k,v in factGraph.namespaces()]))
if DEBUG:
print("## Source Graph ##\n")
print(factGraph.serialize(format='n3'))
Individual.factoryGraph = factGraph
for c in AllClasses(factGraph):
if not isinstance(c.identifier,BNode):
print(c.__repr__(True))
if feature in TopDownTests2Skip:
continue
print(premiseFile, feature, description)
program = list(HornFromN3(StringIO(non_DHL_OWL_Semantics)))
program.extend(
self.network.setupDescriptionLogicProgramming(
factGraph, addPDSemantics=False, constructNetwork=False))
print("Original program")
print(pformat(program))
# timings = []
if REASONING_STRATEGY is None:
sTimeStr = self.calculateEntailments(factGraph)
expectedFacts = Graph(store)
for triple in expectedFacts.parse('.'.join([conclusionFile,'rdf'])):
# closureGraph = ReadOnlyGraphAggregate([self.network.inferredFacts,factGraph])
if triple not in self.network.inferredFacts \
and triple not in factGraph:
print("missing triple %s" % (pformat(triple)))
print(manifest)
print("feature: %s" % feature)
print(description)
print(pformat(list(self.network.inferredFacts)))
raise Exception("Failed test: " + feature)
else:
print("=== Passed! ===")
# print(pformat(list(self.network.inferredFacts)))
print("\n")
testData[manifest] = sTimeStr
store.rollback()
self.setUp()
# self.network.reset()
# self.network._resetinstantiationStats()
#.........这里部分代码省略.........
示例10: read_manifest
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
def read_manifest(item, manifest_file):
triples = []
namespaces = {}
seeAlsoFiles = []
oxdsClasses = ['http://vocab.ox.ac.uk/dataset/schema#Grouping', 'http://vocab.ox.ac.uk/dataset/schema#DataSet']
aggregates = item.list_rdf_objects(item.uri, "ore:aggregates")
g = Graph()
gparsed = g.parse(manifest_file, format='xml')
namespaces = dict(g.namespaces())
#Get the subjects
subjects = {}
for s in gparsed.subjects():
if s in subjects:
continue
if type(s).__name__ == 'URIRef':
if str(s).startswith('file://'):
ss = str(s).replace('file://', '')
if manifest_file in ss:
subjects[s] = URIRef(item.uri)
else:
manifest_file_path, manifest_file_name = os.path.split(manifest_file)
ss = ss.replace(manifest_file_path, '').strip('/')
for file_uri in aggregates:
if ss in str(file_uri):
subjects[s] = URIRef(file_uri)
break
if not s in subjects:
subjects[s] = URIRef(item.uri)
else:
subjects[s] = URIRef(s)
elif type(s).__name__ == 'BNode':
replace_subject = True
for o in gparsed.objects():
if o == s:
replace_subject = False
if replace_subject:
subjects[s] = URIRef(item.uri)
else:
subjects[s] = s
#Get the dataset type
#set the subject uri to item uri if it is of type as defined in oxdsClasses
datasetType = False
for s,p,o in gparsed.triples((None, RDF.type, None)):
if str(o) in oxdsClasses:
if type(s).__name__ == 'URIRef' and len(s) > 0 and str(s) != str(item.uri) and str(subjects[s]) != str(item.uri):
namespaces['owl'] = URIRef("http://www.w3.org/2002/07/owl#")
triples.append((item.uri, 'owl:sameAs', s))
triples.append((item.uri, RDF.type, o))
elif type(s).__name__ == 'BNode' or len(s) == 0 or str(s) == str(item.uri) or str(subjects[s]) == str(item.uri):
gparsed.remove((s, p, o))
subjects[s] = item.uri
#Get the uri for the see also files
for s,p,o in gparsed.triples((None, URIRef('http://www.w3.org/2000/01/rdf-schema#seeAlso'), None)):
if type(o).__name__ == 'URIRef' and len(o) > 0:
obj = str(o)
if obj.startswith('file://'):
obj_path, obj_name = os.path.split(obj)
obj = obj.replace(obj_path, '').strip('/')
for file_uri in aggregates:
if obj in str(file_uri):
seeAlsoFiles.append(file_uri)
gparsed.remove((s, p, o))
#Add remaining triples
for s,p,o in gparsed.triples((None, None, None)):
triples.append((subjects[s], p, o))
return namespaces, triples, seeAlsoFiles
示例11: TestKyotoCabinetGraphCore
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
class TestKyotoCabinetGraphCore(unittest.TestCase):
def setUp(self):
store = "KyotoCabinet"
self.graph = Graph(store=store)
self.path = configString
self.graph.open(self.path, create=True)
def tearDown(self):
self.graph.destroy(self.path)
try:
self.graph.close()
except:
pass
if getattr(self, "path", False) and self.path is not None:
if os.path.exists(self.path):
if os.path.isdir(self.path):
for f in os.listdir(self.path):
os.unlink(self.path + "/" + f)
os.rmdir(self.path)
elif len(self.path.split(":")) == 1:
os.unlink(self.path)
else:
os.remove(self.path)
def test_namespaces(self):
self.graph.bind("dc", "http://http://purl.org/dc/elements/1.1/")
self.graph.bind("foaf", "http://xmlns.com/foaf/0.1/")
self.assert_(len(list(self.graph.namespaces())) == 5)
self.assert_(("foaf", rdflib.term.URIRef(u"http://xmlns.com/foaf/0.1/")) in list(self.graph.namespaces()))
def test_play_journal(self):
self.assertRaises(NotImplementedError, self.graph.store.play_journal, {"graph": self.graph})
def test_readable_index(self):
print(readable_index(111))
def test_create_db(self):
michel = rdflib.URIRef(u"michel")
likes = rdflib.URIRef(u"likes")
pizza = rdflib.URIRef(u"pizza")
cheese = rdflib.URIRef(u"cheese")
self.graph.add((michel, likes, pizza))
self.graph.add((michel, likes, cheese))
self.graph.commit()
self.graph.store.close()
if getattr(self, "path", False) and self.path is not None:
if os.path.exists(self.path):
if os.path.isdir(self.path):
for f in os.listdir(self.path):
os.unlink(self.path + "/" + f)
os.rmdir(self.path)
elif len(self.path.split(":")) == 1:
os.unlink(self.path)
else:
os.remove(self.path)
self.graph.store.open(self.path, create=True)
ntriples = self.graph.triples((None, None, None))
self.assert_(len(list(ntriples)) == 0)
def test_missing_db_exception(self):
self.graph.store.close()
if getattr(self, "path", False) and self.path is not None:
if os.path.exists(self.path):
if os.path.isdir(self.path):
for f in os.listdir(self.path):
os.unlink(self.path + "/" + f)
os.rmdir(self.path)
elif len(self.path.split(":")) == 1:
os.unlink(self.path)
else:
os.remove(self.path)
self.graph.store.open(self.path, create=True)
ntriples = self.graph.triples((None, None, None))
self.assert_(len(list(ntriples)) == 0)
def test_reopening_db(self):
michel = rdflib.URIRef(u"michel")
likes = rdflib.URIRef(u"likes")
pizza = rdflib.URIRef(u"pizza")
cheese = rdflib.URIRef(u"cheese")
self.graph.add((michel, likes, pizza))
self.graph.add((michel, likes, cheese))
self.graph.commit()
self.graph.store.close()
self.graph.store.open(self.path, create=False)
ntriples = self.graph.triples((None, None, None))
self.assert_(len(list(ntriples)) == 2)
def test_reopening_missing_db(self):
self.graph.store.close()
self.assertRaises(ValueError, self.graph.store.open, ("/tmp/NotAnExistingDB"), create=False)
def test_isopen_db(self):
self.assert_(self.graph.store.is_open() == True)
self.graph.store.close()
self.assert_(self.graph.store.is_open() == False)
示例12: GraphMemoryTestCase
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
class GraphMemoryTestCase(unittest.TestCase):
store_name = 'Agamemnon'
settings1 = {
'agamemnon.keyspace' : 'memory',
'agamemnon.host_list' : '["localhost:9160"]',
'agamemnon.rdf_namespace_base' : 'http://www.example.org/rdf/',
}
settings2 = {
'agamemnon.keyspace' : 'memory',
'agamemnon.host_list' : '["localhost:9160"]',
'agamemnon.rdf_namespace_base' : 'http://www.example.org/rdf/',
}
def setUp(self):
self.graph1 = Graph(store=self.store_name)
self.graph2 = Graph(store=self.store_name)
self.graph1.open(self.settings1, True)
self.graph2.open(self.settings2, True)
self.oNS = Namespace("http://www.example.org/rdf/things#")
self.sNS = Namespace("http://www.example.org/rdf/people#")
self.pNS = Namespace("http://www.example.org/rdf/relations/")
self.graph1.bind('people',self.sNS)
self.graph1.bind('relations',self.pNS)
self.graph1.bind('things',self.oNS)
self.graph2.bind('people',self.sNS)
self.graph2.bind('relations',self.pNS)
self.graph2.bind('things',self.oNS)
self.michel = self.sNS.michel
self.tarek = self.sNS.tarek
self.alice = self.sNS.alice
self.bob = self.sNS.bob
self.likes = self.pNS.likes
self.hates = self.pNS.hates
self.named = self.pNS.named
self.pizza = self.oNS.pizza
self.cheese = self.oNS.cheese
def tearDown(self):
self.graph1.close()
self.graph2.close()
def addStuff(self,graph):
graph.add((self.tarek, self.likes, self.pizza))
graph.add((self.tarek, self.likes, self.cheese))
graph.add((self.michel, self.likes, self.pizza))
graph.add((self.michel, self.likes, self.cheese))
graph.add((self.bob, self.likes, self.cheese))
graph.add((self.bob, self.hates, self.pizza))
graph.add((self.bob, self.hates, self.michel)) # gasp!
graph.add((self.bob, self.named, Literal("Bob")))
def removeStuff(self,graph):
graph.remove((None, None, None))
def testBind(self):
store = self.graph1.store
self.assertEqual(store.namespace(""), Namespace("http://www.example.org/rdf/"))
self.assertEqual(store.namespace('people'),self.sNS)
self.assertEqual(store.namespace('relations'),self.pNS)
self.assertEqual(store.namespace('things'),self.oNS)
self.assertEqual(store.namespace('blech'),None)
self.assertEqual("", store.prefix(Namespace("http://www.example.org/rdf/")))
self.assertEqual('people',store.prefix(self.sNS))
self.assertEqual('relations',store.prefix(self.pNS))
self.assertEqual('things',store.prefix(self.oNS))
self.assertEqual(None,store.prefix("blech"))
self.assertEqual(len(list(self.graph1.namespaces())), 7)
def testRelationshipToUri(self):
uri = self.graph1.store.rel_type_to_ident('likes')
self.assertEqual(uri, URIRef("http://www.example.org/rdf/likes"))
uri = self.graph1.store.rel_type_to_ident('emotions:likes')
self.assertEqual(uri, URIRef("emotions:likes"))
self.graph1.bind('emotions','http://www.emo.org/')
uri = self.graph1.store.rel_type_to_ident('emotions:likes')
self.assertEqual(uri, URIRef("http://www.emo.org/likes"))
def testNodeToUri(self):
node = self.graph1.store._ds.create_node('blah', 'bleh')
uri = self.graph1.store.node_to_ident(node)
self.assertEqual(uri, URIRef("http://www.example.org/rdf/blah#bleh"))
self.graph1.bind("bibble", "http://www.bibble.com/rdf/bibble#")
node = self.graph1.store._ds.create_node('bibble', 'babble')
uri = self.graph1.store.node_to_ident(node)
self.assertEqual(uri, URIRef("http://www.bibble.com/rdf/bibble#babble"))
def testUriToRelationship(self):
rel_type = self.graph1.store.ident_to_rel_type(URIRef("http://www.example.org/rdf/likes"))
self.assertEqual(rel_type, 'likes')
#.........这里部分代码省略.........
示例13: Literal
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
# -- (part 2) manually add a triple to the graph --
g.add((URIRef(u"http://example.com/bar"), RDFS.label, Literal("bar")))
# NOTE: predicat RDFS.label will be extended as a full URI: http://www.w3.org/2000/01/rdf-schema#label
# bind a namespace prefix for the example URI reference
g.bind("ex", "http://example.com/")
# serialise the graph in the Turtle RDF syntax
print g.serialize(destination=None, format="turtle", base=None, encoding=None)
# -- (part 3) parse XML/RDF data provided in a string into the graph store --
print "Number of triples in the graph: %i" % len(g)
g.parse(data=rdf_xml_data, format="application/rdf+xml")
print "Number of triples in the graph after parsing the string: %i" % len(g)
# check the actual namespaces bound in the graph store
# NOTE: there should be one additional namespace after parsing the string
for ns in g.namespaces():
print "Prefix: %s => URI: %s" % ns
# serialise the graph
print "\nContents of Graph store in Turtle format:\n========================================\n"
print g.serialize(destination=None, format="turtle")
# manually retrieve the names of artists stored in a graph
for artist in g.objects(subject=None, predicate=URIRef("http://www.recshop.fake/cd#artist")):
print artist
示例14: main
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
#.........这里部分代码省略.........
for fileN in options.rules:
if options.ruleFacts and not options.sparqlEndpoint:
factGraph.parse(fileN, format='n3')
print("Parsing RDF facts from ", fileN)
if options.builtins:
import imp
userFuncs = imp.load_source('builtins', options.builtins)
rs = HornFromN3(fileN,
additionalBuiltins=userFuncs.ADDITIONAL_FILTERS)
else:
rs = HornFromN3(fileN)
nsBinds.update(rs.nsMapping)
ruleSet.formulae.extend(rs)
#ruleGraph.parse(fileN, format='n3')
ruleSet.nsMapping = nsBinds
for prefix, uri in list(nsBinds.items()):
namespace_manager.bind(prefix, uri, override=False)
closureDeltaGraph = Graph()
closureDeltaGraph.namespace_manager = namespace_manager
factGraph.namespace_manager = namespace_manager
if not options.sparqlEndpoint:
for fileN in facts:
factGraph.parse(fileN, format=options.inputFormat)
if options.imports:
for owlImport in factGraph.objects(predicate=OWL_NS.imports):
factGraph.parse(owlImport)
print("Parsed Semantic Web Graph.. ", owlImport)
if facts:
for pref, uri in factGraph.namespaces():
nsBinds[pref] = uri
if options.stdin:
assert not options.sparqlEndpoint, (
"Cannot use --stdin with --sparqlEndpoint")
factGraph.parse(sys.stdin, format=options.inputFormat)
# Normalize namespace mappings
# prune redundant, rdflib-allocated namespace prefix mappings
new_ns_mgr = NamespaceManager(factGraph)
from FuXi.Rete.Util import CollapseDictionary
for k, v in CollapseDictionary(dict([(k, v) for k, v in
factGraph.namespaces()])).items():
new_ns_mgr.bind(k, v)
factGraph.namespace_manager = new_ns_mgr
if options.normalForm:
NormalFormReduction(factGraph)
if not options.sparqlEndpoint:
workingMemory = generateTokenSet(factGraph)
if options.builtins:
import imp
userFuncs = imp.load_source('builtins', options.builtins)
rule_store, rule_graph, network = SetupRuleStore(
makeNetwork=True, additionalBuiltins=userFuncs.ADDITIONAL_FILTERS)
else:
rule_store, rule_graph, network = SetupRuleStore(makeNetwork=True)
network.inferredFacts = closureDeltaGraph
network.nsMap = nsBinds
if options.dlp:
示例15: GraphCassandraTestCase
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import namespaces [as 别名]
class GraphCassandraTestCase(unittest.TestCase):
store_name = 'Agamemnon'
settings1 = {
'agamemnon.keyspace' : 'testagamemnon1',
'agamemnon.host_list' : '["localhost:9160"]',
'agamemnon.rdf_namespace_base' : 'http://www.example.org/',
}
settings2 = {
'agamemnon.keyspace' : 'testagamemnon2',
'agamemnon.host_list' : '["localhost:9160"]',
'agamemnon.rdf_namespace_base' : 'http://www.example.org/',
}
def setUp(self):
self.graph1 = Graph(store=self.store_name)
self.graph2 = Graph(store=self.store_name)
self.graph1.open(self.settings1, True)
self.graph2.open(self.settings2, True)
self.oNS = Namespace("http://www.example.org/things#")
self.sNS = Namespace("http://www.example.org/people#")
self.pNS = Namespace("http://www.example.org/relations/")
self.graph1.bind('people',self.sNS)
self.graph1.bind('relations',self.pNS)
self.graph1.bind('things',self.oNS)
self.graph2.bind('people',self.sNS)
self.graph2.bind('relations',self.pNS)
self.graph2.bind('things',self.oNS)
self.michel = self.sNS.michel
self.tarek = self.sNS.tarek
self.alice = self.sNS.alice
self.bob = self.sNS.bob
self.likes = self.pNS.likes
self.hates = self.pNS.hates
self.named = self.pNS.named
self.pizza = self.oNS.pizza
self.cheese = self.oNS.cheese
def tearDown(self):
self.graph1.close()
self.graph2.close()
def addStuff(self,graph):
graph.add((self.tarek, self.likes, self.pizza))
graph.add((self.tarek, self.likes, self.cheese))
graph.add((self.michel, self.likes, self.pizza))
graph.add((self.michel, self.likes, self.cheese))
graph.add((self.bob, self.likes, self.cheese))
graph.add((self.bob, self.hates, self.pizza))
graph.add((self.bob, self.hates, self.michel)) # gasp!
graph.add((self.bob, self.named, Literal("Bob")))
def removeStuff(self,graph):
graph.remove((None, None, None))
def testBind(self):
store = self.graph1.store
self.assertEqual(store.namespace(""), Namespace("http://www.example.org/"))
self.assertEqual(store.namespace('people'),self.sNS)
self.assertEqual(store.namespace('relations'),self.pNS)
self.assertEqual(store.namespace('things'),self.oNS)
self.assertEqual(store.namespace('blech'),None)
self.assertEqual("", store.prefix(Namespace("http://www.example.org/")))
self.assertEqual('people',store.prefix(self.sNS))
self.assertEqual('relations',store.prefix(self.pNS))
self.assertEqual('things',store.prefix(self.oNS))
self.assertEqual(None,store.prefix("blech"))
self.assertEqual(len(list(self.graph1.namespaces())), 7)
def testRelationshipToUri(self):
uri = self.graph1.store.rel_type_to_ident('likes')
self.assertEqual(uri, URIRef("http://www.example.org/likes"))
uri = self.graph1.store.rel_type_to_ident('emotions:likes')
self.assertEqual(uri, URIRef("emotions:likes"))
self.graph1.bind('emotions','http://www.emo.org/')
uri = self.graph1.store.rel_type_to_ident('emotions:likes')
self.assertEqual(uri, URIRef("http://www.emo.org/likes"))
def testNodeToUri(self):
node = self.graph1.store._ds.create_node('blah', 'bleh')
uri = self.graph1.store.node_to_ident(node)
self.assertEqual(uri, URIRef("http://www.example.org/blah#bleh"))
self.graph1.bind("bibble", "http://www.bibble.com/rdf/bibble#")
node = self.graph1.store._ds.create_node('bibble', 'babble')
uri = self.graph1.store.node_to_ident(node)
self.assertEqual(uri, URIRef("http://www.bibble.com/rdf/bibble#babble"))
def testUriToRelationship(self):
rel_type = self.graph1.store.ident_to_rel_type(URIRef("http://www.example.org/likes"))
self.assertEqual(rel_type, 'likes')
#.........这里部分代码省略.........