rdflib讀取和儲存
阿新 • • 發佈:2019-02-11
構建三元組後,需要對圖進行儲存到本地,並進行讀取
程式碼示例:
1. 利用sleepycat進行rdf資料持久化
#coding:utf8 import rdflib graph = rdflib.Graph('Sleepycat', identifier='lhq') # first time create the store: graph.open('db', create=True) # work with the graph: s = rdflib.URIRef('牛膝') p = rdflib.URIRef('功效屬性') o = rdflib.URIRef('活血') graph.add((s, p, o)) # when done! graph.close() g_t = rdflib.Graph('Sleepycat', identifier='lhq') # 新建圖,指定資料庫 g_t.open('db') # 開啟資料庫並進行操作 print len(g_t) g_t.close()
2.利用serialize將資料以一定規範儲存到硬碟中
主要用到了兩個函式
serialize:將資料序列化儲存到本地
<span style="font-size:18px;">serialize(destination=None, format='xml', base=None, encoding=None, **args) Serialize the Graph to destination 將圖序列化到指定地點 If destination is None serialize method returns the serialization as a string. Format defaults to xml (AKA rdf/xml). 如果該處為空,則返回一個字串。預設格式為xml(AKA rdf/xml) Format support can be extended with plugins, but ‘xml’, ‘n3’, ‘turtle’, ‘nt’, ‘pretty-xml’, trix’ are built in.<span style="font-family: Arial, Helvetica, sans-serif;">支援的格式可以利用外掛進行擴充套件,但‘xml’,‘n3’,‘turtle’,‘nt’,‘pretty-xml’,‘trix’已經被建立了</span>
parse:解析本地檔案,讀取資料
<span style="font-size:18px;">parse(source=None, publicID=None, format='xml', location=None, file=None, data=None, **args)[source] Parse source adding the resulting triples to its own context (sub graph of this graph). 解析源資料並將三元組新增到圖中 See rdflib.graph.Graph.parse() for documentation on arguments. Returns: The graph into which the source was parsed. In the case of n3 it returns the root context.</span>
#coding:utf8
import rdflib
# graph = rdflib.Graph('Sleepycat')
#first time create the store:
# graph.open('myRDFLibStore.rdf', create = True)
graph = rdflib.Graph()
s = rdflib.URIRef('牛膝')
p = rdflib.URIRef('功效屬性')
o = rdflib.URIRef('活血')
graph.add((s, p, o))
# 以n3格式儲存
graph.serialize('zhongyao.rdf', format='n3')
s = rdflib.URIRef('http://www.example.org/牛膝')
p = rdflib.URIRef('http://www.example.org/功效屬性')
o = rdflib.URIRef('http://www.example.org/活血')
g1 = rdflib.Graph()
g1.add((s, p, o))
g1.serialize('zhongyao1.rdf') # 預設以'xml'格式儲存
g2 = rdflib.Graph()
g2.parse('zhongyao1.rdf', format='xml') # 解析rdf檔案時,需要指定格式
subject = g2.subjects(p, o)
for i in subject:
print i