本文整理汇总了Python中rdflib.ConjunctiveGraph.remove方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.remove方法的具体用法?Python ConjunctiveGraph.remove怎么用?Python ConjunctiveGraph.remove使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.ConjunctiveGraph
的用法示例。
在下文中一共展示了ConjunctiveGraph.remove方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_mediator
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
def update_mediator(params):
#Write user metadata and save the rdf file
if not ('username' in params and params['username']):
return False
det = get_mediator_details(params['username'])
graph = Graph()
graph.parse(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']))
for prefix, url in namespaces.iteritems():
graph.bind(prefix, URIRef(url))
uri = URIRef(det['uri'])
if 'firstname' in params and params['firstname']:
graph.remove((uri, namespaces['foaf']['firstName'], None))
graph.add((uri, namespaces['foaf']['firstName'], Literal(params['firstname'])))
if 'lastname' in params and params['lastname']:
graph.remove((uri, namespaces['foaf']['lastName'], None))
graph.add((uri, namespaces['foaf']['lastName'], Literal(params['lastname'])))
if 'email' in params and params['email']:
graph.remove((uri, namespaces['foaf']['mbox'], None))
graph.add((uri, namespaces['foaf']['mbox'], Literal(params['email'])))
if 'title' in params and params['title']:
graph.remove((uri, namespaces['foaf']['title'], None))
graph.add((uri, namespaces['foaf']['title'], Literal(params['title'])))
if 'department' in params and params['department']:
graph.remove((uri, namespaces['dcterms']['isPartOf'], None))
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()
return True
示例2: change_status
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [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
示例3: get_graph_from_sparql_results
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
def get_graph_from_sparql_results(sparql_json, named_graph=None):
if len(sparql_json['results']['bindings']) == 0:
return ConjunctiveGraph(), 0
sparql_vars = sparql_json['head']['vars']
if 'g' in sparql_vars:
if not named_graph:
named_graph = sparql_json['results']['bindings'][0]['g']['value']
sparql_vars.remove('g')
triple_levels = RDFModel.get_context_triples(sparql_json['head']['vars'])
nr_levels = len(triple_levels)
if named_graph:
named_graph = URIRef(named_graph)
graph = ConjunctiveGraph(identifier=named_graph)
graph.namespace_manager = namespace_manager
for binding in sparql_json['results']['bindings']:
binding_levels = RDFModel.get_context_levels(len(binding.keys()))
for s, p, o in triple_levels[:binding_levels]:
subject = URIRef(binding[s]['value'])
if binding[s]['type'] == 'bnode':
subject = BNode(binding[s]['value'])
predicate = URIRef(binding[p]['value'])
obj = RDFModel.get_object_from_sparql_result(binding[o])
graph.add((subject, predicate, obj))
# materialize inferences
for subject, obj in graph.subject_objects(
predicate=URIRef("http://www.openarchives.org/ore/terms/isAggregatedBy")):
graph.add((obj, URIRef("http://www.openarchives.org/ore/terms/aggregates"), subject))
graph.remove((subject, URIRef("http://www.openarchives.org/ore/terms/isAggregatedBy"), obj))
return graph, nr_levels
示例4: update_vocab_uri_in_statusfile
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
def update_vocab_uri_in_statusfile(userid, oldprefix, newprefix, oldvocabdir, newvocabdir):
olduri = "http://vocab.ox.ac.uk/%s"%oldprefix
newuri = "http://vocab.ox.ac.uk/%s"%newprefix
mediatorfile = os.path.join(ag.mediatorsdir, '%s.rdf'%userid)
vocabstatusfile = os.path.join(newvocabdir, 'status.rdf')
if not os.path.isfile(mediatorfile) or not os.path.isfile(vocabstatusfile):
return False
#update uri in mediator file
rdf_str = None
f = codecs.open(mediatorfile, 'r', 'utf-8')
rdf_str = f.read()
f.close()
rdf_str = rdf_str.replace(olduri, newuri)
rdf_str = rdf_str.replace(oldvocabdir, newvocabdir)
f = codecs.open(mediatorfile, 'w', 'utf-8')
f.write(rdf_str)
f.close()
#update uri in vocab status file
rdf_str = None
f = codecs.open(vocabstatusfile, 'r', 'utf-8')
rdf_str = f.read()
f.close()
rdf_str = rdf_str.replace(olduri, newuri)
rdf_str = rdf_str.replace(oldvocabdir, newvocabdir)
f = codecs.open(vocabstatusfile, 'w', 'utf-8')
f.write(rdf_str)
f.close()
#Remove editorial note 0
graph = Graph()
graph.parse(vocabstatusfile)
for s, p, o in graph.triples((URIRef(newuri), namespaces['skos']['editorialNote'], Literal(vocab_editorial_descriptions[0]))):
graph.remove((s, p, o))
rdf_str = None
rdf_str = graph.serialize()
f = codecs.open(vocabstatusfile, 'w', 'utf-8')
f.write(rdf_str)
f.close()
return True
示例5: ManifestHelper
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
#.........这里部分代码省略.........
for ans_s, ans_p, ans_o in self.g.triples((s, p, o)):
count += 1
if count > 0:
return True
else:
return False
def list_objects(self, s, p):
objects = []
if not type(self.g).__name__ in ['ConjunctiveGraph', 'Graph']:
return objects
if s == '*':
s = None
if p == '*':
p = None
if not isinstance(s, URIRef) and not isinstance(s, BNode) and not s == None:
s = self.urihelper.get_uriref(s)
if not isinstance(p, URIRef) and not p == None:
p = self.urihelper.parse_uri(p)
for o in self.g.objects(s, p):
objects.append(o)
return objects
def add_triple(self, s, p, o):
if not isinstance(s, URIRef) and not isinstance(s, BNode):
s = self.urihelper.get_uriref(s)
if not isinstance(p, URIRef):
p = self.urihelper.parse_uri(p)
if not isinstance(o, URIRef) and not isinstance(o, Literal) and not isinstance(o, BNode):
if not isinstance(o, basestring):
o = unicode(o)
o = self.urihelper.parse_uri(o, return_Literal_not_Exception=True)
self.g.add((s, p, o))
self.g.commit()
return
def add_namespace(self, prefix, uri):
if not isinstance (prefix, basestring):
raise TypeError('Add namespace: prefix is not of type string or unicode')
if not isinstance(uri, (URIRef, Namespace)):
if not isinstance(uri, basestring):
raise TypeError('Add namespace: namespace is not of type string or unicode')
if not isinstance(prefix, unicode):
prefix = unicode(prefix)
if isinstance(uri, basestring) and not isinstance(uri, unicode):
uri = unicode(uri)
self.namespaces[prefix] = self.urihelper.get_namespace(uri)
if prefix not in self.urihelper.namespaces:
self.urihelper.namespaces[prefix] = self.urihelper.get_namespace(uri)
self.g.bind(prefix, self.namespaces[prefix])
return
def del_namespace(self, prefix, ns):
if prefix in self.namespaces:
del self.namespaces[prefix]
return
def del_triple(self, s, p, o=None):
if not type(self.g).__name__ in ['ConjunctiveGraph', 'Graph']:
return
if s == '*':
s = None
if p == '*':
p = None
if o == '*':
o = None
if not isinstance(s, URIRef) and not isinstance(s, BNode) and not s == None:
s = self.urihelper.get_uriref(s)
if not isinstance(p, URIRef) and not p == None:
p = self.urihelper.parse_uri(p)
if not isinstance(o, URIRef) and not isinstance(o, Literal) and not isinstance(o, BNode) and not o == None:
if not isinstance(o, basestring):
o = unicode(o)
o = self.urihelper.parse_uri(o, return_Literal_not_Exception=True)
self.g.remove((s, p, o))
return
def get_graph(self):
return self.g
def to_string(self, format="xml"):
if type(self.g).__name__ in ['ConjunctiveGraph', 'Graph'] and len(self.g)>0:
self.g.commit()
ans_str = self.g.serialize(format=format, encoding="utf-8")+"\n"
return ans_str
else:
return u'<?xml version="1.0" encoding="UTF-8"?>\n'
示例6: TestInfer
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
class TestInfer(TestCase):
def setUp(self):
self.model = ConjunctiveGraph()
add_default_schemas(self.model)
self.model.parse(data=MINI_FOAF_ONTOLOGY, format='turtle')
def test_class(self):
fooNS = Namespace('http://example.org/')
self.model.parse(data=FOAF_DATA, format='turtle')
inference = Infer(self.model)
s = [fooNS['me.jpg'], RDF['type'], RDFS['Class']]
found = list(self.model.triples(s))
self.assertEqual(len(found), 0)
inference._rule_class()
s = [fooNS['me.jpg'], RDF['type'], RDFS['Class']]
found = list(self.model.triples(s))
self.assertEqual(len(found), 1)
def test_inverse_of(self):
fooNS = Namespace('http://example.org/')
self.model.parse(data=FOAF_DATA, format='turtle')
inference = Infer(self.model)
depiction = (None, FOAF['depiction'], fooNS['me.jpg'])
size = len(self.model)
found_statements = list(self.model.triples(depiction))
self.assertEqual(len(found_statements), 0)
inference._rule_inverse_of()
found_statements = list(self.model.triples(depiction))
self.assertEqual(len(found_statements), 1)
# we should've added one statement.
self.assertEqual(len(self.model), size + 1)
size = len(self.model)
inference._rule_inverse_of()
# we should already have both versions in our model
self.assertEqual(len(self.model), size)
def test_validate_types(self):
fooNS = Namespace('http://example.org/')
self.model.parse(data=FOAF_DATA, format='turtle')
inference = Infer(self.model)
errors = list(inference._validate_types())
self.assertEqual(len(errors), 0)
s = (fooNS['document'], DC['title'], Literal("bleem"))
self.model.add(s)
errors = list(inference._validate_types())
self.assertEqual(len(errors), 1)
def test_validate_undefined_properties_in_schemas(self):
fooNS = Namespace('http://example.org/')
inference = Infer(self.model)
errors = list(inference._validate_undefined_properties())
self.assertEqual(len(errors), 0)
def test_validate_undefined_properties_in_inference(self):
fooNS = Namespace('http://example.org/')
foafNS = Namespace('http://xmlns.com/foaf/0.1/')
self.model.parse(data=FOAF_DATA, format='turtle')
inference = Infer(self.model)
errors = list(inference._validate_undefined_properties())
self.assertEqual(len(errors), 2)
inference = Infer(self.model)
errors = list(inference._validate_property_types())
self.assertEqual(len(errors), 0)
s = (fooNS['me.jpg'], FOAF['firstName'], Literal("name"))
self.model.add(s)
errors = list(inference._validate_property_types())
self.assertEqual(len(errors), 1)
startswith = 'Domain of '
self.assertEqual(errors[0][:len(startswith)], startswith)
self.assertTrue('http://example.org/me.jpg' in errors[0])
endswith = 'http://xmlns.com/foaf/0.1/Person'
self.assertEqual(errors[0][-len(endswith):], endswith)
self.model.remove(s)
errors = list(inference._validate_property_types())
self.assertEqual(len(errors), 0)
s = (fooNS['foo.txt'], RDF['type'], FOAF['Document'])
self.model.add(s)
s = (fooNS['me.jpg'], FOAF['depicts'], FOAF['foo.txt'])
self.model.add(s)
errors = list(inference._validate_property_types())
self.assertEqual(len(errors), 1)
startswith = 'Range of '
self.assertEqual(errors[0][:len(startswith)], startswith)
self.assertTrue('http://example.org/me.jpg' in errors[0])
endswith = 'http://www.w3.org/2002/07/owl#Thing'
self.assertEqual(errors[0][-len(endswith):], endswith)
self.model.remove(s)
#.........这里部分代码省略.........
示例7: ContextTestCase
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
class ContextTestCase(unittest.TestCase):
store_name = 'default'
path = None
storetest = True
create = True
michel = URIRef(u'michel')
tarek = URIRef(u'tarek')
bob = URIRef(u'bob')
likes = URIRef(u'likes')
hates = URIRef(u'hates')
pizza = URIRef(u'pizza')
cheese = URIRef(u'cheese')
c1 = URIRef(u'context-1')
c2 = URIRef(u'context-2')
def setUp(self):
self.graph = ConjunctiveGraph(store=self.store_name)
self.graph.destroy(self.path)
if isinstance(self.path, type(None)):
if self.store_name == "SQLite":
self.path = mkstemp(prefix='test',dir='/tmp')
else:
self.path = mkdtemp(prefix='test',dir='/tmp')
self.graph.open(self.path, create=self.create)
def tearDown(self):
self.graph.destroy(self.path)
try:
self.graph.close()
except:
pass
import os
if hasattr(self,'path') 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 get_context(self, identifier):
assert isinstance(identifier, URIRef) or \
isinstance(identifier, BNode), type(identifier)
return Graph(store=self.graph.store, identifier=identifier,
namespace_manager=self)
def addStuff(self):
tarek = self.tarek
michel = self.michel
bob = self.bob
likes = self.likes
hates = self.hates
pizza = self.pizza
cheese = self.cheese
c1 = self.c1
graph = Graph(self.graph.store, c1)
graph.add((tarek, likes, pizza))
graph.add((tarek, likes, cheese))
graph.add((michel, likes, pizza))
graph.add((michel, likes, cheese))
graph.add((bob, likes, cheese))
graph.add((bob, hates, pizza))
graph.add((bob, hates, michel)) # gasp!
def removeStuff(self):
tarek = self.tarek
michel = self.michel
bob = self.bob
likes = self.likes
hates = self.hates
pizza = self.pizza
cheese = self.cheese
c1 = self.c1
graph = Graph(self.graph.store, c1)
graph.remove((tarek, likes, pizza))
graph.remove((tarek, likes, cheese))
graph.remove((michel, likes, pizza))
graph.remove((michel, likes, cheese))
graph.remove((bob, likes, cheese))
graph.remove((bob, hates, pizza))
graph.remove((bob, hates, michel)) # gasp!
def addStuffInMultipleContexts(self):
c1 = self.c1
c2 = self.c2
triple = (self.pizza, self.hates, self.tarek) # revenge!
# add to default context
self.graph.add(triple)
# add to context 1
graph = Graph(self.graph.store, c1)
graph.add(triple)
# add to context 2
graph = Graph(self.graph.store, c2)
graph.add(triple)
def testConjunction(self):
#.........这里部分代码省略.........
示例8: WineRDFDatabase
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
class WineRDFDatabase(object):
def __init__(self):
"""Creates the RDF graph"""
print 'Initialize RDF graph, set namespace mappings'
self.classes = self.valid_classes()
self.graph = ConjunctiveGraph()
self.graph.bind('base', BASE)
self.graph.bind('rdf', RDF)
self.graph.bind('rdfs', RDFS)
self.graph.bind('vocab', VOCAB)
self.graph.bind('wine', WINE)
self.graph.bind('wine_prod', WINE_PROD)
self.graph.bind('whisky', WHISKY)
for wine in Wine.objects.all():
self.add_wine(wine)
for wine_producer in WineProducer.objects.all():
self.add_wine_producer(wine_producer)
print 'Added %i triples ' % len(self.graph)
def valid_classes(self):
"""Returns a list of wine styles in the wines.rdf"""
classes = set()
root = etree.parse(os.path.join(PROJECT_ROOT, 'backend', 'wine.rdf'))
for elem in root.iter():
id = '{%s}ID' % RDF
if id in elem.attrib:
classes.add(elem.attrib[id])
return classes
def add_wine_producer(self, wine_producer):
"""Add a WineProducer model to the graph"""
self.graph.add((URIRef(WINE_PROD[str(wine_producer.id)]),
URIRef(RDF['type']), URIRef(BASE['Winery'])))
self.graph.add((URIRef(WINE_PROD[str(wine_producer.id)]),
URIRef(RDF['type']), URIRef(VOCAB['organzation'])))
self.graph.add((URIRef(WINE_PROD[str(wine_producer.id)]),
URIRef(RDF['label']), Literal(wine_producer.name)))
self.graph.add((URIRef(WINE_PROD[str(wine_producer.id)]),
URIRef(VOCAB['address']), Literal(wine_producer.address)))
def add_wine(self, wine):
"""Add a Wine model to the graph"""
self.graph.add((URIRef(WINE[str(wine.id)]), URIRef(BASE['hasMaker']),
URIRef(WINE_PROD[str(wine.wine_producer.id)])))
self.graph.add((URIRef(WINE[str(wine.id)]), URIRef(RDFS['label']),
Literal(wine.name)))
region = wine.region
if region == 'California' or region.startswith('Santa Barbara'):
region = 'CaliforniaRegion'
if region in self.classes:
self.graph.add((URIRef(WINE[str(wine.id)]), URIRef(RDF['locatedIn']),
URIRef(BASE[region])))
else:
self.graph.add((URIRef(WINE[str(wine.id)]), URIRef(RDF['locatedIn']),
Literal(region)))
style = wine.style.replace(' ','')
if style.endswith('Port'):
style = 'Port'
if style in self.classes:
self.graph.add((URIRef(WINE[str(wine.id)]), URIRef(RDF['type']),
URIRef(BASE[style])))
#else:
# self.graph.add((URIRef(WINE[str(wine.id)]), URIRef(RDF['type']),
# Literal(style)))
if wine.color:
self.graph.add((URIRef(WINE[str(wine.id)]), URIRef(BASE['hasColor']),
URIRef(BASE[wine.color.replace(' ','')])))
if wine.percentage_alcohol:
self.graph.add((URIRef(WINE[str(wine.id)]),
URIRef(WHISKY['abv']), Literal(wine.percentage_alcohol)))
if wine.vintage:
self.graph.add((URIRef(WINE[str(wine.id)]),
URIRef(BASE['hasVintageYear']), Literal(wine.vintage)))
def remove_resource(self, resource):
"""Removes from the graph all triples that have `resource` as the
subject or object"""
for triple in self.query_graph(subj=resource, obj=resource):
self.graph.remove(triple)
def query_graph(self, subj=None, pred=None, obj=None, exhaustive=False):
"""Return a graph of all triples with subect `sub`, predicate `pred`
OR object `obj. If `exhaustive`, return all subelements of the given
arguments (If sub is http://127.0.0.1/api/v1/wine/, return
http://127.0.0.1/api/v1/wine/{s} for all s). Arguments must be of type
URIRef or Literal"""
g = ConjunctiveGraph()
count = 0
if not isinstance(subj, list):
subj = [subj]
for sub in subj:
for uri_s, uri_p, uri_o in sorted(self.graph):
s, p, o = str(uri_s), str(uri_p), str(uri_o)
if exhaustive:
s = s.rpartition('/')[0]
#.........这里部分代码省略.........
示例9: len
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
parts = re.split(r' +', label)
label = ' '.join(l.lower().capitalize() for l in parts).strip()
position = 0
else:
parts = line.split("\t")
label = parts.pop().strip()
range = parts.pop(0).strip()
position = len(parts) + 1
# if there's no range then we've got a chunk of text that needs
# to be added to the last concept we added to the graph
if not range:
uri = range_uri(lc_class[-1][0])
old_label = list(g.objects(uri, SKOS.prefLabel))[0]
new_label = "%s %s" % (old_label, label)
g.remove((uri, SKOS.prefLabel, old_label))
g.add((uri, SKOS.prefLabel, Literal(new_label, 'en')))
continue
lc_class = lc_class[0:position]
lc_class.insert(position, (range, label))
label = '--'.join([c[1] for c in lc_class])
uri = range_uri(range)
g.add((uri, RDF.type, SKOS.Concept))
g.add((uri, SKOS.prefLabel, Literal(label, 'en')))
g.add((uri, SKOS.notation, Literal(range, datatype=LCC)))
if position == 0:
g.add((LCCO, SKOS.hasTopConcept, uri))
示例10: TabLinker
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
#.........这里部分代码省略.........
"""
# Use the rowhierarchy to create a unique qname for the cell's contents,
# give the source_cell's original value as extra argument
self.log.debug("Parsing HierarchicalRowHeader")
# Add all the values
for (index, value) in self.rowhierarchy[i].items():
prop = self.property_dimensions[index]
self.row_dimensions.setdefault(i,{})
self.row_dimensions[i][self.namespaces['scope'][prop]]= Literal(value)
# Relate the hierarchical headers
keys = self.rowhierarchy[i].keys()
for i in range(len(keys)-1):
prop_top = self.namespaces['scope'][self.property_dimensions[keys[i]]]
prop_sub = self.namespaces['scope'][self.property_dimensions[keys[i+1]]]
self.graph.add((prop_sub, self.namespaces['tablink']['subPropertyOf'], prop_top))
def parseRowLabel(self, i, j):
"""
Create relevant triples for the cell marked as Label (i, j are row and column)
"""
self.log.debug("Parsing Row Label")
# Get the QName of the HierarchicalRowHeader cell that this label belongs to, based on the rowhierarchy for this row (i)
hierarchicalRowHeader_value_qname = self.getQName(self.rowhierarchy[i])
prefLabels = self.graph.objects(self.namespaces['scope'][hierarchicalRowHeader_value_qname], self.namespaces['skos'].prefLabel)
for label in prefLabels :
# If the hierarchicalRowHeader QName already has a preferred label, turn it into a skos:altLabel
self.graph.remove((self.namespaces['scope'][hierarchicalRowHeader_value_qname],self.namespaces['skos'].prefLabel,label))
self.graph.add((self.namespaces['scope'][hierarchicalRowHeader_value_qname],self.namespaces['skos'].altLabel,label))
self.log.debug("Turned skos:prefLabel {} for {} into a skos:altLabel".format(label, hierarchicalRowHeader_value_qname))
# Add the value of the label cell as skos:prefLabel to the header cell
# self.graph.add((self.namespaces['scope'][hierarchicalRowHeader_value_qname], self.namespaces['skos'].prefLabel, Literal(self.source_cell.value, 'nl')))
# Record that this source_cell_qname is the label for the HierarchicalRowHeader cell
# self.graph.add((self.namespaces['scope'][self.source_cell_qname], self.namespaces['tablink']['isLabel'], self.namespaces['scope'][hierarchicalRowHeader_value_qname]))
def parseRowHeader(self, i, j) :
"""
Create relevant triples for the cell marked as RowHeader (i, j are row and column)
"""
rowHeaderValue = ""
# Don't attach the cell value to the namespace if it's already a URI
isURI = urlparse(str(self.source_cell.value))
if isURI.scheme and isURI.netloc:
rowHeaderValue = URIRef(self.source_cell.value)
else:
self.source_cell_value_qname = self.source_cell.value
rowHeaderValue = Literal(self.source_cell_value_qname)
# Get the properties to use for the row headers
prop = self.property_dimensions[j]
self.row_dimensions.setdefault(i,{})
self.row_dimensions[i][self.namespaces['scope'][prop]]= rowHeaderValue
return
def parseColHeader(self, i, j) :
"""
示例11: ContextTestCase
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
class ContextTestCase(unittest.TestCase):
storetest = True
store_name = "default"
create = True
michel = URIRef(u"michel")
tarek = URIRef(u"tarek")
bob = URIRef(u"bob")
likes = URIRef(u"likes")
hates = URIRef(u"hates")
pizza = URIRef(u"pizza")
cheese = URIRef(u"cheese")
c1 = URIRef(u"context-1")
c2 = URIRef(u"context-2")
def setUp(self):
self.graph = ConjunctiveGraph(self.store_name, self.identifier)
self.graph.open(self.tmppath, create=self.create)
# self.store = plugin.get(self.store_name, store.Store)(
# configuration=self.tmppath, identifier=self.identifier)
# self.graph = ConjunctiveGraph(self.store_name, identifier=self.identifier)
# self.graph.destroy(self.tmppath)
# self.graph.open(self.tmppath)
def tearDown(self):
# self.graph.destroy(self.tmppath)
try:
self.graph.close()
except:
pass
if os.path.exists(self.tmppath):
os.unlink(self.tmppath)
def get_context(self, identifier):
assert isinstance(identifier, URIRef) or isinstance(identifier, BNode), type(identifier)
return Graph(store=self.graph.store, identifier=identifier, namespace_manager=self)
def addStuff(self):
tarek = self.tarek
michel = self.michel
bob = self.bob
likes = self.likes
hates = self.hates
pizza = self.pizza
cheese = self.cheese
c1 = self.c1
graph = Graph(self.graph.store, c1)
graph.add((tarek, likes, pizza))
graph.add((tarek, likes, cheese))
graph.add((michel, likes, pizza))
graph.add((michel, likes, cheese))
graph.add((bob, likes, cheese))
graph.add((bob, hates, pizza))
graph.add((bob, hates, michel)) # gasp!
def removeStuff(self):
tarek = self.tarek
michel = self.michel
bob = self.bob
likes = self.likes
hates = self.hates
pizza = self.pizza
cheese = self.cheese
c1 = self.c1
graph = Graph(self.graph.store, c1)
graph.remove((tarek, likes, pizza))
graph.remove((tarek, likes, cheese))
graph.remove((michel, likes, pizza))
graph.remove((michel, likes, cheese))
graph.remove((bob, likes, cheese))
graph.remove((bob, hates, pizza))
graph.remove((bob, hates, michel)) # gasp!
def addStuffInMultipleContexts(self):
c1 = self.c1
c2 = self.c2
triple = (self.pizza, self.hates, self.tarek) # revenge!
# add to default context
self.graph.add(triple)
# add to context 1
graph = Graph(self.graph.store, c1)
graph.add(triple)
# add to context 2
graph = Graph(self.graph.store, c2)
graph.add(triple)
def testConjunction(self):
self.addStuffInMultipleContexts()
triple = (self.pizza, self.likes, self.pizza)
# add to context 1
graph = Graph(self.graph.store, self.c1)
graph.add(triple)
self.assertEquals(len(self.graph), len(graph))
def testAdd(self):
self.addStuff()
#.........这里部分代码省略.........
示例12: graph_plan
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
#.........这里部分代码省略.........
def __get_pattern_node(p):
if p not in patterns:
patterns[p] = BNode('tp_{}'.format(len(patterns)))
return patterns[p]
def __inc_tree_length(tree, l):
if tree not in tree_lengths:
tree_lengths[tree] = 0
tree_lengths[tree] += l
def __add_variable(p_node, vid, subject=True):
sub_node = BNode(str(vid).replace('?', 'var_'))
if subject:
plan_graph.add((p_node, AGORA.subject, sub_node))
else:
plan_graph.add((p_node, AGORA.object, sub_node))
plan_graph.set((sub_node, RDF.type, AGORA.Variable))
plan_graph.set((sub_node, RDFS.label, Literal(str(vid), datatype=XSD.string)))
def include_path(elm, p_seeds, p_steps):
elm_uri = __extend_uri(prefixes, elm)
path_g = plan_graph.get_context(elm_uri)
b_tree = BNode(elm_uri)
s_trees.add(b_tree)
path_g.set((b_tree, RDF.type, AGORA.SearchTree))
path_g.set((b_tree, AGORA.fromType, elm_uri))
for seed in p_seeds:
path_g.add((b_tree, AGORA.hasSeed, URIRef(seed)))
previous_node = b_tree
__inc_tree_length(b_tree, len(p_steps))
for j, step in enumerate(p_steps):
prop = step.get('property')
b_node = BNode(previous_node.n3() + prop)
if j < len(p_steps) - 1 or pattern[1] == RDF.type:
path_g.add((b_node, AGORA.onProperty, __extend_uri(prefixes, prop)))
path_g.add((b_node, AGORA.expectedType, __extend_uri(prefixes, step.get('type'))))
path_g.add((previous_node, AGORA.next, b_node))
previous_node = b_node
p_node = __get_pattern_node(pattern)
path_g.add((previous_node, AGORA.byPattern, p_node))
for i, tp_plan in enumerate(ef_plan):
paths = tp_plan.get('paths')
pattern = tp_plan.get('pattern')
hints = tp_plan.get('hints')
context = BNode('space_{}'.format(tp_plan.get('context')))
for path in paths:
steps = path.get('steps')
seeds = path.get('seeds')
if not len(steps) and len(seeds):
include_path(pattern[2], seeds, steps)
elif len(steps):
ty = steps[0].get('type')
include_path(ty, seeds, steps)
for t in s_trees:
plan_graph.set((t, AGORA.length, Literal(tree_lengths.get(t, 0), datatype=XSD.integer)))
pattern_node = __get_pattern_node(pattern)
plan_graph.add((context, AGORA.definedBy, pattern_node))
plan_graph.set((context, RDF.type, AGORA.SearchSpace))
plan_graph.add((pattern_node, RDF.type, AGORA.TriplePattern))
(sub, pred, obj) = pattern
if isinstance(sub, BNode):
__add_variable(pattern_node, str(sub))
elif isinstance(sub, URIRef):
plan_graph.add((pattern_node, AGORA.subject, sub))
if isinstance(obj, BNode):
__add_variable(pattern_node, str(obj), subject=False)
elif isinstance(obj, Literal):
node = BNode(str(obj).replace(' ', ''))
plan_graph.add((pattern_node, AGORA.object, node))
plan_graph.set((node, RDF.type, AGORA.Literal))
plan_graph.set((node, AGORA.value, Literal(str(obj), datatype=XSD.string)))
else:
plan_graph.add((pattern_node, AGORA.object, obj))
plan_graph.add((pattern_node, AGORA.predicate, pred))
if pred == RDF.type:
if 'check' in hints:
plan_graph.add((pattern_node, AGORA.checkType, Literal(hints['check'], datatype=XSD.boolean)))
sub_expected = plan_graph.subjects(predicate=AGORA.expectedType)
for s in sub_expected:
expected_types = list(plan_graph.objects(s, AGORA.expectedType))
for et in expected_types:
plan_graph.remove((s, AGORA.expectedType, et))
q_expected_types = [plan_graph.qname(t) for t in expected_types]
expected_types = [d for d in expected_types if
not set.intersection(set(fountain.get_type(plan_graph.qname(d)).get('super')),
set(q_expected_types))]
for et in expected_types:
plan_graph.add((s, AGORA.expectedType, et))
return plan_graph
示例13: ConjunctiveGraph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
from rdflib import ConjunctiveGraph
g = ConjunctiveGraph()
g.parse('../data/hm_17_1.rss')
#len(g)
import sys
sys.path.append('../')
from model.namespaces import *
from model.bibo import Article
from rdfalchemy import rdfSubject
nsm = g._get_namespace_manager()
nsm.bind('prism', 'http:prism.com')
print g.serialize()
#PRISM2 = Namespace('http://prismstandard.org/namespaces/basic/2.0/')
for s, p, o in g.triples((None, RDF.type, RSS.item)):
g.add((s, p, BIBO.Article))
g.remove((s, p, o))
rdfSubject.db = g
l = list(Article.ClassInstances())
a = l[1]
print a.title
print a.creators
print a.sPg
示例14: TabLinker
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
#.........这里部分代码省略.........
self.namespaces["scope"][self.source_cell_value_qname],
self.namespaces["skos"]["broader"],
self.namespaces["scope"][parent_value_qname],
)
)
except:
self.log.debug(i, j, "Top of hierarchy")
# Get the properties to use for the row headers
try:
properties = []
for dim_qname in self.property_dimensions[j]:
properties.append(dim_qname)
except KeyError:
self.log.debug("({}.{}) No row dimension for cell".format(i, j))
self.row_dimensions.setdefault(i, []).append((self.source_cell_value_qname, properties))
def parseRowLabel(self, i, j):
"""
Create relevant triples for the cell marked as Label (i, j are row and column)
"""
self.log.debug("Parsing Row Label")
# Get the QName of the HierarchicalRowHeader cell that this label belongs to, based on the rowhierarchy for this row (i)
hierarchicalRowHeader_value_qname = self.getQName(self.rowhierarchy[i])
prefLabels = self.graph.objects(
self.namespaces["scope"][hierarchicalRowHeader_value_qname], self.namespaces["skos"].prefLabel
)
for label in prefLabels:
# If the hierarchicalRowHeader QName already has a preferred label, turn it into a skos:altLabel
self.graph.remove(
(self.namespaces["scope"][hierarchicalRowHeader_value_qname], self.namespaces["skos"].prefLabel, label)
)
self.graph.add(
(self.namespaces["scope"][hierarchicalRowHeader_value_qname], self.namespaces["skos"].altLabel, label)
)
self.log.debug(
"Turned skos:prefLabel {} for {} into a skos:altLabel".format(label, hierarchicalRowHeader_value_qname)
)
# Add the value of the label cell as skos:prefLabel to the header cell
self.graph.add(
(
self.namespaces["scope"][hierarchicalRowHeader_value_qname],
self.namespaces["skos"].prefLabel,
Literal(self.source_cell.value, "nl"),
)
)
# Record that this source_cell_qname is the label for the HierarchicalRowHeader cell
self.graph.add(
(
self.namespaces["scope"][self.source_cell_qname],
self.namespaces["d2s"]["isLabel"],
self.namespaces["scope"][hierarchicalRowHeader_value_qname],
)
)
def parseRowHeader(self, i, j):
"""
Create relevant triples for the cell marked as RowHeader (i, j are row and column)
"""
rowHeaderValue = ""
示例15: ContextTestCase
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import remove [as 别名]
class ContextTestCase(unittest.TestCase):
store = 'default'
slow = True
tmppath = None
def setUp(self):
try:
self.graph = ConjunctiveGraph(store=self.store)
except ImportError:
raise SkipTest(
"Dependencies for store '%s' not available!" % self.store)
if self.store == "SQLite":
_, self.tmppath = mkstemp(
prefix='test', dir='/tmp', suffix='.sqlite')
else:
self.tmppath = mkdtemp()
self.graph.open(self.tmppath, create=True)
self.michel = URIRef(u'michel')
self.tarek = URIRef(u'tarek')
self.bob = URIRef(u'bob')
self.likes = URIRef(u'likes')
self.hates = URIRef(u'hates')
self.pizza = URIRef(u'pizza')
self.cheese = URIRef(u'cheese')
self.c1 = URIRef(u'context-1')
self.c2 = URIRef(u'context-2')
# delete the graph for each test!
self.graph.remove((None, None, None))
def tearDown(self):
self.graph.close()
if os.path.isdir(self.tmppath):
shutil.rmtree(self.tmppath)
else:
os.remove(self.tmppath)
def addStuff(self):
tarek = self.tarek
michel = self.michel
bob = self.bob
likes = self.likes
hates = self.hates
pizza = self.pizza
cheese = self.cheese
c1 = self.c1
graph = Graph(self.graph.store, c1)
graph.add((tarek, likes, pizza))
graph.add((tarek, likes, cheese))
graph.add((michel, likes, pizza))
graph.add((michel, likes, cheese))
graph.add((bob, likes, cheese))
graph.add((bob, hates, pizza))
graph.add((bob, hates, michel)) # gasp!
def removeStuff(self):
tarek = self.tarek
michel = self.michel
bob = self.bob
likes = self.likes
hates = self.hates
pizza = self.pizza
cheese = self.cheese
c1 = self.c1
graph = Graph(self.graph.store, c1)
graph.remove((tarek, likes, pizza))
graph.remove((tarek, likes, cheese))
graph.remove((michel, likes, pizza))
graph.remove((michel, likes, cheese))
graph.remove((bob, likes, cheese))
graph.remove((bob, hates, pizza))
graph.remove((bob, hates, michel)) # gasp!
def addStuffInMultipleContexts(self):
c1 = self.c1
c2 = self.c2
triple = (self.pizza, self.hates, self.tarek) # revenge!
# add to default context
self.graph.add(triple)
# add to context 1
graph = Graph(self.graph.store, c1)
graph.add(triple)
# add to context 2
graph = Graph(self.graph.store, c2)
graph.add(triple)
def testConjunction(self):
if self.store == "SQLite":
raise SkipTest("Skipping known issue with __len__")
self.addStuffInMultipleContexts()
triple = (self.pizza, self.likes, self.pizza)
# add to context 1
graph = Graph(self.graph.store, self.c1)
graph.add(triple)
self.assertEqual(len(self.graph), len(graph))
#.........这里部分代码省略.........