2012-01-25 70 views

回答

10

這不是很複雜。首先,一些必要的進口:

from StringIO import StringIO 
from rdflib import Graph, URIRef 

我使用StringIO這裏,以免造成文件。相反,我只是列舉了一些內容,這些內容的類似文件的對象:

contents = '''\ 
subject1\tpredicate1\tobject1 
subject2\tpredicate2\tobject2''' 
tabfile = StringIO(contents) 

然後創建一個圖形,並加載所有三元它:

graph = rdflib.Graph() 

for line in tabfile: 
    triple = line.split()    # triple is now a list of 3 strings 
    triple = (URIRef(t) for t in triple) # we have to wrap them in URIRef 
    graph.add(triple)     # and add to the graph 

現在你有全圖在內存中(當然,假設你有足夠的內存)。您現在可以打印它:

print graph.serialize(format='nt') 

# prints: 
# <subject1> <predicate1> <object1> . 
# <subject2> <predicate2> <object2> . 
+0

Nitpick:你是以N3格式序列化圖形。由於原始海報要求N-Triples,我只是想我會指出這兩種格式不一樣。 –

+0

@JeenBroekstra:謝謝,我沒有仔細閱讀這篇文章。我會糾正我的答案。 – DzinX