當前位置: 首頁>>代碼示例>>Python>>正文


Python ConjunctiveGraph.bind方法代碼示例

本文整理匯總了Python中rdflib.Graph.ConjunctiveGraph.bind方法的典型用法代碼示例。如果您正苦於以下問題:Python ConjunctiveGraph.bind方法的具體用法?Python ConjunctiveGraph.bind怎麽用?Python ConjunctiveGraph.bind使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在rdflib.Graph.ConjunctiveGraph的用法示例。


在下文中一共展示了ConjunctiveGraph.bind方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
    def __init__(self, path=None):
        self.__dict__ = self.__shared_state
        if (self.data == None):
            if (path == None):
                raise ValueError("djubby's configuration MUST be initialized a first time, read http://code.google.com/p/djubby/wiki/GettingStarted")
            else:
                self.path = os.path.abspath(path)
                logging.debug("Reading djubby's configuration from %s..." % self.path)
                if (not os.path.exists(self.path)):
                    raise ValueError("Not found a proper file at '%s' with a configuration for djubby. Please, provide a right path" % self.path)

                data = ConjunctiveGraph()
                data.bind("conf", ns.config) 
                try:
                    data.load(path, format='n3') 
                except Exception, e:
                    raise ValueError("Not found a proper N3 file at '%s' with a configuration for djubby. Please, provide a valid N3 file" % self.path)

                self.data = data
                try:
                    self.graph = self.get_value("sparqlDefaultGraph")
                    self.endpoint = self.get_value("sparqlEndpoint")
                except Exception, e:
                    raise ValueError("Not found the graph not the endpoint that it's supposed djubby have to query. Please, provide a right donfiguration")

                logging.info("Using <%s> as default graph to query the endpoint <%s>" % (self.graph, self.endpoint))
                self.__class__.__dict__['_Configuration__shared_state']["data"] = data #FIXME
開發者ID:kiivihal,項目名稱:djubby,代碼行數:29,代碼來源:configuration.py

示例2: make_rdf_graph

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
def make_rdf_graph(movies):
    mg=ConjunctiveGraph()

    mg.bind('fb',FB)
    mg.bind('dc',DC)
    for movie in movies:
        
        # Make a movie node
        movie_node=IVA_MOVIE[movie['id']]    
        mg.add((movie_node,DC['title'],Literal(movie['title'])))
        
        # Make the director node, give it a name and link it to the movie
        dir_node=IVA_PERSON[movie['director']['id']]
        mg.add((movie_node,FB['film.film.directed_by'],dir_node))
        mg.add((dir_node,DC['title'],Literal(movie['director']['name'])))

        for actor in movie['actors']:
            # The performance node is a blank node -- it has no URI
            performance=BNode()
            
            # The performance is connected to the actor and the movie
            actor_node=IVA_PERSON[actor['id']]
            
            mg.add((actor_node,DC['title'],Literal(actor['name'])))
            mg.add((performance,FB['film.performance.actor'],actor_node))
            # If you had the name of the role, you could also add it to the
            # performance node, e.g.
            # mg.add((performance,FB['film.performance.role'],Literal('Carrie Bradshaw')))

            mg.add((movie_node,FB['film.film.performances'],performance))

    return mg
開發者ID:abhik1368,項目名稱:study-semantic-web,代碼行數:34,代碼來源:IVAtoRDF.py

示例3: to_rdf

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
    def to_rdf(self, format="settings"):
        """Convert the RdfSerializer store into RDF."""
        graph = Graph()
        for k, v in self.NAMESPACES.iteritems():
            graph.bind(k, v)

        for g in self.subgraphs:
            graph += g

        if format == "settings":
            format = settings.RDF_SERIALIZATION

        return graph.serialize(format=format)
開發者ID:spsu,項目名稱:sylph,代碼行數:15,代碼來源:RdfSerializer.py

示例4: parse

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
    def parse(self, source, graph):
        # we're currently being handed a Graph, not a ConjunctiveGraph
        assert graph.store.context_aware # is this implied by formula_aware
        assert graph.store.formula_aware

        conj_graph = ConjunctiveGraph(store=graph.store)
        conj_graph.default_context = graph # TODO: CG __init__ should have a default_context arg
        # TODO: update N3Processor so that it can use conj_graph as the sink
        sink = Sink(conj_graph)
        if False:
            sink.quantify = lambda *args: True
            sink.flatten = lambda *args: True
        baseURI = graph.absolutize(source.getPublicId() or source.getSystemId() or "")
        p = N3Processor("nowhere", sink, baseURI=baseURI) # pass in "nowhere" so we can set data instead
        p.userkeys = True # bah
        p.data = source.getByteStream().read() # TODO getCharacterStream?
        p.parse()
        for prefix, namespace in p.bindings.items():
            conj_graph.bind(prefix, namespace)
開發者ID:Ju2ender,項目名稱:watchdog,代碼行數:21,代碼來源:N3Parser.py

示例5: toRDF

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
    def toRDF(self):
        """
        Print a message into RDF in XML format
        """
        
        #rdf graph
        store = ConjunctiveGraph()
        
        #namespaces        
        store.bind('sioc', SIOC)
        store.bind('foaf', FOAF)
        store.bind('rdfs', RDFS)
        store.bind('dc', DC)
        store.bind('dct', DCT)

        #message node
        message = URIRef(self.getUri())
        store.add((message, RDF.type, SIOC["Post"]))

        #document node
        doc = URIRef(self.getUri()+'.rdf')
        store.add((doc, RDF.type, FOAF["Document"]))
        store.add((doc, FOAF["primaryTopic"], message))
        
        try:
                 
            store.add((message, SIOC['id'], Literal(self.getSwamlId())))
            store.add((message, SIOC['link'], URIRef(self.getXhtmlUrl())))  
            store.add((message, SIOC['has_container'],URIRef(self.config.get('base')+'forum')))   
            store.add((message, SIOC["has_creator"], URIRef(self.getSender().getUri())))                    
            store.add((message, DC['title'], Literal(self.getSubject()))) 
            store.add((message, DCT['created'], Literal(self.getDate(), datatype=XSD[u'dateTime'])))  
            
            parent = self.getParent()
            if (parent != None):
                store.add((message, SIOC['reply_of'], URIRef(parent)))  
                
            if (len(self.childs) > 0):
                for child in self.childs:
                    store.add((message, SIOC['has_reply'], URIRef(child)))
                
            previous = self.getPreviousByDate()
            if (previous != None):
                store.add((message, SIOC['previous_by_date'], URIRef(previous)))
                
            next = self.getNextByDate()
            if (next != None):
                store.add((message, SIOC['next_by_date'], URIRef(next)))                
            
            store.add((message, SIOC['content'], Literal(self.getBody())))
            
        except Exception, detail:
            print 'Error proccesing message ' + str(self.getId()) + ': ' + str(detail) 
開發者ID:wikier,項目名稱:swaml,代碼行數:55,代碼來源:message.py

示例6: message_board_to_sioc

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
def message_board_to_sioc(dbfile):
    sg=ConjunctiveGraph()
    sg.bind('foaf',FOAF)
    sg.bind('sioc',SIOC)
    sg.bind('dc',DC)
    
    conn=sqlite3.connect(dbfile)
    cur=conn.cursor()

    # Get all the messages and add them to the graph
    cur.execute('SELECT id,title,content,user FROM messages')
    
    for id,title,content,user in cur.fetchall():
        mnode=MB['messages/%d' % id]
        sg.add((mnode,RDF.type,SIOC['Post']))
        sg.add((mnode,DC['title'],Literal(title)))
        sg.add((mnode,SIOC['content'],Literal(content)))
        sg.add((mnode,SIOC['has_creator'],MB['users/%s' % user]))        

    # Get all the users and add them to the graph
    cur.execute('SELECT id,name,email FROM users')
    for id,name,email in cur.fetchall():
        sg.add((mnode,RDF.type,SIOC['User']))
        unode=MB['users/%d' % id]
        sg.add((unode,FOAF['name'],Literal(name)))
        sg.add((unode,FOAF['email'],Literal(email)))        

    # Get subjects
    cur.execute('SELECT id,description FROM subjects')
    for id,description in cur.fetchall():
        sg.add((mnode,RDF.type,DCTERMS['subject']))
        sg.add((MB['subjects/%d' % id],RDFS['label'],Literal(description)))
    
    # Link subject to messages
    cur.execute('SELECT message_id,subject_id FROM message_subjects')
    for mid,sid in cur.fetchall():
        sg.add((MB['messages/%s' % mid],SIOC['topic'],MB['subjects/%s'] % sid))

    conn.close()

    return sg
開發者ID:abhik1368,項目名稱:study-semantic-web,代碼行數:43,代碼來源:message_board_to_sioc.py

示例7: MySQL

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
#this works too
#store = MySQL(identifier,configuration)

#use rdflib to create schema for instance, that is, create doens't "create the db, rather, it creates the schema for the db
store.open(configString, create=False)
#print store.identifier

###################
# a ConjunctiveGraph
###################
conjgraph = ConjunctiveGraph(store=store,identifier=URIRef('http://purl.org/linguistics/gold'))

data = Namespace('http://purl.org/linguistics/data/')

conjgraph.bind('data',data)

#probably no triples should be added the conjgraph
#conjgraph.add((data['lingsign123'], data['orthographicRep'], Literal('dog')))
#conjgraph.add((data['lingsign456'], data['orthographicRep'], Literal('cat')))
#conjgraph.add((data['lingsign789'], data['orthographicRep'], Literal('fish')))

#print conjgraph.default_context
conjgraph.commit()
"""


##############
# Plain Graph1
################
"""
開發者ID:Uduse,項目名稱:e-linguistics,代碼行數:32,代碼來源:store_practice.py

示例8: Namespace

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
import urllib
from simplejson import loads
from csv import reader

JB = Namespace("http://semprog.com/schemas/jobboard#")
DC = Namespace("http://purl.org/dc/elements/1.1/")
FOAF = Namespace("http://xmlns.com/foaf/0.1/")
COMPANY = Namespace("http://purl.org/rss/1.0/modules/company/")

# Connecion to Sesame
con=connection('http://freerisk.org:8280/openrdf-sesame/')
con.use_repository('joblistings')
con.addnamespace('company',str(COMPANY))

cg=ConjunctiveGraph()
cg.bind('dc',DC)
cg.bind('jobboard',JB)

# Find companies with ticker symbols
res=con.query('select ?id ?ticker where {?id company:symbol ?ticker .}')

# Loop over the results
for row in res:
    company=URIRef(row['id']['value'])
    ticker=row['ticker']['value']
    
    url='http://ichart.finance.yahoo.com/table.csv?s=%s&a=00&b=28&c=2008&d=00&e=28&f=2009&g=m&ignore=.csv' % ticker
    
    rows=[row for row in reader(urllib.urlopen(url))]

    current=float(rows[1][6])
開發者ID:abhik1368,項目名稱:study-semantic-web,代碼行數:33,代碼來源:yahoo_finance_update.py

示例9: update_rdf_for_conversion

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
def update_rdf_for_conversion(prefix, vocab_properties, rdf_vocab_properties):

    #(id, base, prefix) = get_vocab_base(vocabfile)
    html_vocab_properties = {}
    html_vocab_properties['format'] = 'text/html'
    html_vocab_properties['name'] = "%s.html"%os.path.splitext(rdf_vocab_properties['name'])[0]
    html_vocab_properties['path'] = rdf_vocab_properties['path'].replace(rdf_vocab_properties['name'], html_vocab_properties['name'])
    html_vocab_properties['uri'] = rdf_vocab_properties['uri'].replace(rdf_vocab_properties['name'], html_vocab_properties['name'])

    newrdf_vocab_properties = {}
    newrdf_vocab_properties['format'] = 'application/rdf+xml'
    newrdf_vocab_properties['name'] = "%s_modified.rdf"%os.path.splitext(rdf_vocab_properties['name'])[0]
    newrdf_vocab_properties['path'] = rdf_vocab_properties['path'].replace(rdf_vocab_properties['name'], newrdf_vocab_properties['name'])
    newrdf_vocab_properties['uri'] = rdf_vocab_properties['uri'].replace(rdf_vocab_properties['name'], newrdf_vocab_properties['name'])

    graph = Graph()
    graph.parse(rdf_vocab_properties['path'])

    subject = None
    for s in graph.subjects(namespaces['rdf']['type'], URIRef(namespaces['owl']['Ontology'])):
        subject = s

    #graph2 = Graph()
    graph_ns = []
    for nsprefix, nsurl in graph.namespaces():
        graph_ns.append(str(nsurl))
    for prefix, url in namespaces.iteritems():
        if not str(url) in graph_ns:
            graph.bind(prefix, URIRef(url))

    
    #properties = get_vocab_properties(prefix)
    #subject = None
    #for s in graph.subjects(namespaces['dc']['title'], None):
    #    subject = s
    #if not subject:
    #    for s in graph.subjects(namespaces['dcterms']['title'], None):
    #        subject = s
    #if not subject:
    #    for s in graph.subjects(namespaces['dc']['creator'], None):
    #        subject = s
    #if not subject:
    #    for s in graph.subjects(namespaces['dcterms']['creator'], None):
    #        subject = s

    formatNode1 = BNode()
    formatNode2 = BNode()

    #Add vocabulary properties identifier and format
    graph.add((subject, namespaces['dc']['identifier'], URIRef(rdf_vocab_properties['uri'])))
    graph.add((subject, namespaces['dcterms']['isVersionOf'], URIRef(vocab_properties['preferredNamespaceUri'])))
    graph.add((subject, namespaces['dcterms']['hasFormat'], URIRef(rdf_vocab_properties['uri'])))
    graph.add((subject, namespaces['dcterms']['hasFormat'], URIRef(html_vocab_properties['uri'])))
    graph.add((subject, namespaces['vann']['preferredNamespaceUri'], URIRef(vocab_properties['preferredNamespaceUri'])))
    graph.add((subject, namespaces['vann']['preferredNamespacePrefix'], URIRef(vocab_properties['preferredNamespacePrefix'])))

    graph.add((URIRef(html_vocab_properties['uri']), namespaces['rdf']['type'], URIRef(namespaces['dctype']['Text'])))
    graph.add((URIRef(html_vocab_properties['uri']), namespaces['dc']['format'], formatNode1))
    graph.add((formatNode1, namespaces['rdf']['value'], Literal('text/html')))
    graph.add((formatNode1, namespaces['rdfs']['label'], Literal('HTML')))
    graph.add((formatNode1, namespaces['rdf']['type'], URIRef(namespaces['dcterms']['IMT'])))

    graph.add((URIRef(rdf_vocab_properties['uri']), namespaces['rdf']['type'], URIRef(namespaces['dctype']['Text'])))
    graph.add((URIRef(rdf_vocab_properties['uri']), namespaces['dc']['format'], formatNode2))
    graph.add((formatNode2, namespaces['rdf']['value'], Literal('application/rdf+xml')))
    graph.add((formatNode2, namespaces['rdfs']['label'], Literal('RDF')))
    graph.add((formatNode2, namespaces['rdf']['type'], URIRef(namespaces['dcterms']['IMT'])))

    #Add rdfs:isDefinedBy for each class / property / term of the vocabulary
    #Find if schema is rdfs / owl. This defines the possible types (rdf:type) for each class / property / term
    #testo = vocab_type_definitions_test['rdfs']
    #subjects = []
    #subs = graph.subjects(namespaces['rdf']['type'], URIRef(testo))
    #for s in subs:
    #    subjects.append(s)
    #if subjects:
    #    objects = vocab_type_definitions_rdfs
    #else:
    #    objects = vocab_type_definitions_owl

    #For all subjects that are of the type found above, add rdfs:isDefinedBy
    #for o in objects: 
    #    subs = graph.subjects(namespaces['rdf']['type'], o)
    #    for s in subs:
    #        graph.add((s, namespaces['rdfs']['isDefinedBy'], URIRef(vocab_properties['preferredNamespaceUri'])))

    list_of_terms = get_terms(rdf_vocab_properties['path'])
    for s in list_of_terms:
        graph.add((URIRef(s), namespaces['rdfs']['isDefinedBy'], URIRef(vocab_properties['preferredNamespaceUri'])))

    rdf_str = None
    rdf_str = graph.serialize(format="pretty-xml")
    #f = codecs.open(newrdf_vocab_properties['path'], 'w', 'utf-8')
    f = codecs.open(newrdf_vocab_properties['path'], 'w')
    f.write(rdf_str)
    f.close()
    return (newrdf_vocab_properties, html_vocab_properties)
開發者ID:anusharanganathan,項目名稱:Vocab-ox,代碼行數:99,代碼來源:conversion_helper_rdf.py

示例10: Namespace

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
from rdflib.Graph import ConjunctiveGraph
from rdflib import Namespace, BNode, Literal, RDF, URIRef
import csv
import pysesame

JB = Namespace("http://semprog.com/schemas/jobboard#")
GEO = Namespace('http://www.w3.org/2003/01/geo/wgs84_pos#')

lg=ConjunctiveGraph()
lg.bind('geo',GEO)

for city,lat,long in csv.reader(file('city_locations.csv','U')):
    lg.add((JB[city],GEO['lat'],Literal(float(lat))))
    lg.add((JB[city],GEO['long'],Literal(float(long))))
    
data=lg.serialize(format='xml')
print data
c=pysesame.connection('http://semprog.com:8280/openrdf-sesame/')
c.use_repository('joblistings')
print c.postdata(data)


    
開發者ID:abhik1368,項目名稱:study-semantic-web,代碼行數:22,代碼來源:load_city_locations.py

示例11: Graph

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
_hdlr = logging.StreamHandler()
_hdlr.setFormatter(logging.Formatter('%(name)s %(levelname)s: %(message)s'))
_logger.addHandler(_hdlr)

from rdflib.Graph import ConjunctiveGraph as Graph
from rdflib import plugin
from rdflib.store import Store
from rdflib import Namespace
from rdflib import Literal
from rdflib import URIRef

from rdflib.sparql.bison import Parse
store = Graph()

# with some care this could be made less redundant
store.bind("dc", "http://http://purl.org/dc/elements/1.1/")
store.bind("foaf", "http://xmlns.com/foaf/0.1/")
store.bind("dc", 'http://purl.org/dc/elements/1.1/')
store.bind("rdf", 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
store.bind("rdfs", 'http://www.w3.org/2000/01/rdf-schema#')
store.bind("owl", 'http://www.w3.org/2002/07/owl#') 
store.bind("vs", 'http://www.w3.org/2003/06/sw-vocab-status/ns#')

# Create a namespace object for the Friend of a friend namespace.
foaf = Namespace("http://xmlns.com/foaf/0.1/")
dc = Namespace('http://purl.org/dc/elements/1.1/')
rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
rdfs = Namespace('http://www.w3.org/2000/01/rdf-schema#')
owl = Namespace('http://www.w3.org/2002/07/owl#')
vs = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#')
開發者ID:foaf,項目名稱:foaftown,代碼行數:32,代碼來源:specgen4b.py

示例12: Namespace

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
from rdflib.Graph import ConjunctiveGraph
from rdflib import Namespace, BNode, Literal, RDF, URIRef
import csv
import pysesame

JOBS = Namespace("http://www.medev.ac.uk/interoperability/rss/1.0/modules/jobs/rss1.0jobsmodule#")
DC = Namespace("http://purl.org/dc/elements/1.1/")
JB = Namespace("http://semprog.com/schemas/jobboard#")
COMPANY = Namespace("http://purl.org/rss/1.0/modules/company/")
RDFS=Namespace('http://www.w3.org/2000/01/rdf-schema#')

jg=ConjunctiveGraph()
jg.bind('jobs',JOBS)
jg.bind('dc',DC)
jg.bind('jobboard',JB)
jg.bind('company',COMPANY)
jg.bind('rdfs',RDFS)

# Incremental counter for vacancy IDs
vid=0

for title,salary,location,company,crunchbase,ticker in csv.reader(file('joblist.csv')):
    # Create the vacancy
    vid+=1
    vacancy=JB[str(vid)]
    jg.add((vacancy,RDF.type,JOBS['Vacancy']))
    jg.add((vacancy,DC['title'],Literal(title)))
    
    location_id=location.lower().replace(' ','_').replace(',','')
    jg.add((vacancy,JB['location'],JB[location_id]))
    jg.add((JB[location_id],DC['title'],Literal(location)))
開發者ID:abhik1368,項目名稱:study-semantic-web,代碼行數:33,代碼來源:convert_jobs.py

示例13: __init__

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
class rdf_transform:
    
    def __init__(self):
        
        self.g = Graph('IOMemory')
        self.g.bind('dc', dublin_core)
        self.g.bind('foaf', FOAF)
        self.g.bind('time-entry', owl_time)
        self.g.bind('letter', letter_ns)
        self.g.bind('owl', owl)
        self.g.bind('ex', exam)
        self.g.bind('geo', geo)
        self.g.bind('base', base_uri)


    def create_rdf_letter (self, letters):
        '''
          creates an rdf representation of letter used to load into the triple store
        '''
        for l in letters:
            correspondence = base_uri + "letters/resource/" + l.type + '/' + urllib.quote(l.correspondent) + '/' + str(l.id) + '/rdf'
            self.add_author(correspondence, "Charles Dickens")
            self.add_subject(correspondence, "letter")
            self.add_time(correspondence, str(l.letter_date)+'T00:00:00')
            self.add_correspondent(correspondence, l.correspondent)
    
            #self.add_place(correspondence, parse_text.find_geographical(l.letter_text))
            place = ''
            try:
                place = str(l.letter_place)
            #unicode errors are text related
            except UnicodeError:
                pass
            
            if place is not '':
                self.add_place(correspondence, place)
                
            self.add_letter_text(correspondence, l.letter_text)
            self.add_salutation(correspondence, l.correspondent, l.salutation)
            
            #for line in l.letter_text.splitlines():
            #    if len(line.strip()) > 1:
            #        self.add_open(correspondence, parse_text.parse_salutation_line(line))
                #this section will parse for proper names in due course
                #commented out whilst code is being ported
                #letter_name = parse_text.parseProperNames(text)
               # print"names, ", letter_name
                
                #for name in letter_name:
                #    letter_rdf += "<letter:personReferred>%s</letter:personReferred>" %(name)
                                   
            letter_quotes = parse_text.parse_balanced_quotes(l.letter_text)
            for quote in letter_quotes:
                 if str(quote[0:1]).isupper and "!" not in quote:
                     if quote == "ALL THE YEAR ROUND" or quote=="HOUSEHOLD WORDS" or quote== "Household Words":
                         self.add_magazine(correspondence, parse_text.stripPunc(quote))
                     else:
                         self.add_text(correspondence, parse_text.stripPunc(quote))
                
        letter_rdf = self.g.serialize(format="pretty-xml", max_depth=3)
        return letter_rdf
    
    
    def create_rdf_end (self):
        ''' function to create an endpoint in rdf/xml '''
        correspondence = base_uri 
        
        letter = {}  
        letter = dbase.get_endpoint_rdf()
    
        letter_items = letter.items()
        letter_items.sort()
    
        works = set()
        works = dbase.get_books()
        
        for url, text in letter_items:

            try:
                correspondence = base_uri + "letters/resource/dickens/" + urllib.quote(str(text[1])) + '/' + str(url) + '/rdf'
                self.add_author(correspondence, "Charles Dickens")
                self.add_subject(correspondence, "letter")
                self.add_subject(correspondence, "Charles Dickens")
                self.add_subject(correspondence, parse_text.camel_case(str(text[1])))
                self.add_time(correspondence, str(text[3])+'T00:00:00')
                self.add_correspondent(correspondence, str(text[1]))
                self.add_salutation(correspondence, urllib.quote(str(text[1])), str(text[4]))
                place = str(text[5])
                #for line in str(text[2]).splitlines():
                #    self.add_open(correspondence, parse_text.parse_salutation_line(str(text[2])))
                letter = str(text[2])
            #unicode errors are text related
            except UnicodeError:
                pass
            if place is not None:
                self.add_place(correspondence, place)
            
            self.add_letter_text(correspondence, letter)
            
            #this section will parse for proper names in due course
#.........這裏部分代碼省略.........
開發者ID:Spencerx,項目名稱:openletters,代碼行數:103,代碼來源:transform_rdf.py

示例14: schemafy

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
def schemafy(html_file):
    """Extract RDF from RDFa-annotated [html_file]; return a L{Graph} 
    containing the RDF."""

    # create an empty graph and bind some namespaces
    store = Graph()
    store.bind("cc", "http://creativecommons.org/ns#")
    store.bind("dc", "http://purl.org/dc/elements/1.1/")
    store.bind("dcq","http://purl.org/dc/terms/")
    store.bind("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#")
    store.bind("xsd","http://www.w3.org/2001/XMLSchema-datatypes#")
    store.bind("owl","http://www.w3.org/2002/07/owl#")
    store.bind("xhtml", "http://www.w3.org/1999/xhtml/vocab#")

    # parse the source document
    parser = rdfadict.RdfaParser()
    parser.parse_file(file(html_file), "http://creativecommons.org/ns",
                      sink=GraphSink(store))

    # remove undesirable assertions
    remove_assertions(store)

    return store
開發者ID:creativecommons,項目名稱:license.rdf,代碼行數:25,代碼來源:make_schema.py

示例15: Namespace

# 需要導入模塊: from rdflib.Graph import ConjunctiveGraph [as 別名]
# 或者: from rdflib.Graph.ConjunctiveGraph import bind [as 別名]
from rdflib import Namespace, BNode, Literal, RDF, URIRef
from pysesame import connection
import urllib
from simplejson import loads

# Connecion to Sesame
con=connection('http://freerisk.org:8280/openrdf-sesame/')
con.use_repository('joblistings')
con.addnamespace('rdfs','http://www.w3.org/2000/01/rdf-schema#')

JB = Namespace("http://semprog.com/schemas/jobboard#")
DC = Namespace("http://purl.org/dc/elements/1.1/")
FOAF = Namespace("http://xmlns.com/foaf/0.1/")

cg=ConjunctiveGraph()
cg.bind('dc',DC)
cg.bind('jobboard',JB)
cg.bind('foaf',FOAF)

# Find seeAlso URLs containing Crunchbase
res=con.query('select ?id ?url where {?id rdfs:seeAlso ?url . FILTER regex(?url, "crunchbase")}')

# Loop over the results
for row in res:
    company=URIRef(row['id']['value'])
    url=row['url']['value']
    data=urllib.urlopen(url).read()
    record=loads(data)

    # Add company locations
    for loc in record['offices']:
開發者ID:abhik1368,項目名稱:study-semantic-web,代碼行數:33,代碼來源:crunchbase_data.py


注:本文中的rdflib.Graph.ConjunctiveGraph.bind方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。