本文整理汇总了Python中rdflib.Graph.preferredLabel方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.preferredLabel方法的具体用法?Python Graph.preferredLabel怎么用?Python Graph.preferredLabel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.Graph
的用法示例。
在下文中一共展示了Graph.preferredLabel方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_language
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import preferredLabel [as 别名]
def test_language(self):
rec = '''
<marc:record xmlns:marc="http://www.loc.gov/MARC21/slim">
<marc:leader>00000nw a2200000n 4500</marc:leader>
<marc:datafield tag="040" ind2=" " ind1=" ">
<marc:subfield code="a">OCLCD</marc:subfield>
<marc:subfield code="b">nob</marc:subfield>
<marc:subfield code="c">OCLCD</marc:subfield>
</marc:datafield>
<marc:datafield tag="084" ind2=" " ind1="0">
<marc:subfield code="a">ddc</marc:subfield>
<marc:subfield code="c">23no</marc:subfield>
<marc:subfield code="e">nob</marc:subfield>
</marc:datafield>
<marc:datafield tag="153" ind2=" " ind1=" ">
<marc:subfield code="a">564.58</marc:subfield>
<marc:subfield code="e">564.5</marc:subfield>
<marc:subfield code="j">Decapoda (tiarmede blekkspruter)</marc:subfield>
</marc:datafield>
</marc:record>
'''
graph = Graph()
process_record(graph, rec, base_uri='http://test/{object}')
uri = URIRef(u'http://test/564.58')
assert graph.preferredLabel(uri)[0][0] == SKOS.prefLabel
assert graph.preferredLabel(uri)[0][1].language == 'nb'
示例2: Graph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import preferredLabel [as 别名]
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, rdflib
from rdflib import Graph, Namespace, URIRef, Literal, RDF, RDFS
from unidecode import unidecode
SKOS=Namespace("http://www.w3.org/2004/02/skos/core#")
graph = Graph()
graph.parse(sys.argv[1], format='turtle')
for s,p,o in graph.triples( (None, rdflib.RDF.type, SKOS.Concept) ):
result = graph.preferredLabel(s, lang='fi')
if result:
label = result[-1][-1].value
stripped = unidecode(label)
if label != stripped and 'ä'.decode('utf-8') not in label and 'ö'.decode('utf-8') not in label:
graph.add((s, SKOS.altLabel, Literal(stripped, lang='fi')))
for alt in graph.objects(s, SKOS.altLabel):
stripped = unidecode(alt.value)
if stripped != alt.value and 'ä'.decode('utf-8') not in label and 'ö'.decode('utf-8') not in label:
graph.add((s, SKOS.hiddenLabel, Literal(stripped, lang='fi')))
graph.serialize(format='turtle', destination=sys.stdout)
示例3: SemWP
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import preferredLabel [as 别名]
class SemWP(Graph):
def __init__(self, fname='lrmirdfs.ttl',
fmat='turtle'):
if fname != '':
self.g = Graph().parse(fname, format=fmat)
schema = Namespace(u'http://schema.org/')
self.thing = schema.Thing
semwp_ns = Namespace(u'http://ns.pjjk.net/semwp')
else:
self.g = Graph()
schema = Namespace(u'http://schema.org/')
self.thing = schema.Thing
semwp_ns = Namespace(u'http://ns.pjjk.net/semwp')
self.name = None
def resource_label(self, r: URIRef, lang='en'):
# Given SemWP object amd a resource uri and a language code string
# returns the most appropriate label for the resource as a string.
# Uses g.preferredLabel with preferred language but defaults first
# alternative option if possible preferred lang not available
if self.g.preferredLabel(r, lang):
resourcelabel = self.g.preferredLabel(r, lang)[0][1].toPython()
elif self.g.preferredLabel(r):
resourcelabel = self.g.preferredLabel(r)[0][1].toPython()
else:
raise Exception('resource %r has no label' % r)
return
return resourcelabel
def resource_id(self, r: URIRef, lang='en'):
# Given SemWP object amd a resource uri and a language code string
# returns a string that can be used as an id for custom post types
# for that resource.
# Uses g.preferredLabel with preferred language but defaults first
# alternative option if possible preferred lang not available
# bumps to lower case and truncates to 20 chars
resourceid = self.resource_label(r, lang)[:20].lower()
return resourceid
def resource_comment(self, r: URIRef, lang='en'):
# Given SemWP object and a resource uri returns the rdfs comment as a string
# stripped of its HTML cruft, new lines and quotes
# Currently lang is ignored (all in schema comments are in english)
s = MLStripper()
html = self.g.value(r, RDFS.comment, None).toPython()
html += '<br>' # bizarrely, will return null if no html tags at all
s.feed(html)
comment = s.get_data()
comment = comment.replace('\n',' ')
comment = comment.replace("'","")
comment = comment.replace('"','')
comment = comment.replace(')','')
comment = comment.replace('(','')
return comment
def peek(self, iterable):
try:
first = next(iterable)
except StopIteration:
return None
return first, chain([first], iterable)
def top_classes(self):
# give a SemWP object returns a list of rdfs classes that are
# not RDFS.subClass of anything
tclist = []
for c in self.g.subjects(RDF.type, RDFS.Class):
parent = self.peek(self.g.objects(c, RDFS.subClassOf))
if parent is None:
tclist.append(c)
return tclist
def sub_classes(self, c: URIRef, recurse=True):
# Given SemWP object and a class returns a list of rdfs
# subclasses of the class from the current instance of SemWP graph.
# Will descend down through subclasses of subclasses if recurse is
# set to default val of True
sclist = []
if self.g.subjects(RDFS.subClassOf, c):
for sc in self.g.subjects(RDFS.subClassOf, c):
sclist.append(sc)
if recurse:
sclist.extend(self.sub_classes(sc))
return sclist
else:
return sclist
def super_classes(self, c: URIRef, recurse=True):
# Given SemWP object and a class returns a list of classes of which
# the class is a sublass from the current instance of SemWP graph.
# Will ascend up through sperclasses of superclasses if recurse is
# set to default val of True
sclist = []
if self.g.objects(c, RDFS.subClassOf):
for sc in self.g.objects(c, RDFS.subClassOf):
sclist.append(sc)
if recurse:
sclist.extend(self.super_classes(sc))
return sclist
#.........这里部分代码省略.........
示例4: Graph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import preferredLabel [as 别名]
return '' # no difference
else:
return result
g = Graph()
g.parse(sys.argv[1], format='turtle')
concepts = list(g.subjects(SKOS.inScheme, YSO['']))
random.shuffle(concepts)
writer = csv.writer(sys.stdout)
i = 0
for conc in concepts:
vals = [conc]
is_plural = False
for lang,pl_suffix in PLURAL_SUFFIXES.items():
try:
label = g.preferredLabel(conc, lang=lang)[0][1]
if label.endswith(pl_suffix):
is_plural = True
labelSingular = singular(label, lang)
except:
label = labelSingular = ''
vals += [label.encode('UTF-8'), labelSingular.encode('UTF-8')]
if not is_plural:
continue
writer.writerow(vals)
i += 1
if i >= 1000: break
示例5: URIRef
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import preferredLabel [as 别名]
return URIRef(pnr_uri.replace(MMLPNR, LDFPNR['P_']))
elif SUBREG['c'] in pnr_uri:
return URIRef(pnr_uri.replace(SUBREG['c'], LDFPNR['subregion_']))
else:
logging.critical("Cannot convert PNR URI <%s> to LDF equivalent", pnr_uri)
return None
def scaleuri_to_value(scaleuri):
return int(scaleuri.replace(SCALE['c'], ''))
logging.info("Adding PNR mappings and hierarchy...")
count = 0
for ysauri, target in mappings.subject_objects(SKOS.closeMatch):
logging.info("---")
try:
ysalabel = ysa.preferredLabel(ysauri)[0][1]
except IndexError:
logging.warning("YSA URI <%s> has disappeared, skipping", ysauri)
continue
pnruri = ldf_to_pnr_uri(target)
logging.info("YSA: <%s> '%s'", ysauri, ysalabel)
out.add((ysauri, SKOS.prefLabel, Literal(ysalabel, 'fi')))
pnrdata = Graph()
starttime = time.time()
pnrdata.parse(pnruri, format='xml')
endtime = time.time()
logging.debug('Loaded %d triples from %s in %.2f seconds', len(pnrdata), pnruri, endtime-starttime)
try: # prefer Finnish
pnrlabel = pnrdata.preferredLabel(pnruri,lang='fi')[0][1]
except IndexError: # but any language will do
try:
示例6: open
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import preferredLabel [as 别名]
return uris
with open(sys.argv[1], 'rb') as fh:
reader = MARCReader(fh)
for rec in reader:
changed_fields = set()
recid = rec['001'].value()
uri = ysa_uri(recid) # FIXME check 024
# Virojoki (joki), Itämeri, Joensuu, Joroinen -- Kolma
if uri not in (YSA['Y107962'], YSA['Y105038'], YSA['Y94166'], YSA['Y112746']):
continue
logging.info("YSA URI: <%s>", uri)
# check for BT relationships and add
for broader in enriched.objects(uri, SKOS.broader):
btlabel = enriched.preferredLabel(broader, lang='fi')[0][1]
remove_existing_551(rec, btlabel)
logging.info("BT: <%s> '%s'", broader, btlabel)
rec.add_ordered_field(
Field(
tag='551',
indicators = [' ', ' '],
subfields = ['w', 'g'] + label_to_subfields(btlabel)
))
changed_fields.add('551')
# check for NT relationships and add
for narrower in enriched.objects(uri, SKOS.narrower):
ntlabel = enriched.preferredLabel(narrower, lang='fi')[0][1]
remove_existing_551(rec, ntlabel)
logging.info("NT: <%s> '%s'", narrower, ntlabel)
示例7: Graph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import preferredLabel [as 别名]
label = repo.get_label('uusi')
need_inspection = repo.get_issues(state='closed', labels=[label])
ysa_skos = Graph().parse(ysa_file, format='turtle')
yse_skos = Graph().parse(yse_file, format='turtle')
def delete_triples(uri):
yse_skos.remove((URIRef(uri), None, None))
yse_skos.remove((None, None, URIRef(uri)))
def replaced_by(uri, title):
new_uri = lookup(title)
if(new_uri != ''):
yse_skos.remove((None, None, URIRef(uri)))
yse_skos.add((URIRef(uri), dct.isReplacedBy, URIRef(new_uri)))
yse_skos.add((URIRef(uri), OWL.deprecated, Literal('true',datatype=XSD.boolean)))
for issue in need_inspection:
if ('**Termiehdotus Fintossa:**' in issue.body):
md_href = issue.body.split("**Termiehdotus Fintossa:**")[1]
if md_href:
suggestion_uri = ysa + md_href.split('page/')[1].replace(')', '')
yselab = yse_skos.preferredLabel(suggestion_uri, lang='fi')
ysalab = yse_skos.preferredLabel(suggestion_uri, lang='fi')
if yselab != '' and yselab == ysalab: # the suggestion has been taken into YSA with the same prefLabel
print "deleting: " + issue.title
delete_triples(suggestion_uri)
else:
print('add replacedBy to:' + suggestion_uri)
yse_skos.serialize(destination=yse_file, format='turtle')