2013-03-02 129 views
7

我有一個文件.ttl窗體。它有4個屬性/列包含以下形式的四倍:如何使用RDFLib解析.ttl文件?

  1. (id, student_name, student_address, student_phoneno)
  2. (id, faculty_name, faculty_address, faculty_phoneno)

我知道如何用RDFLib解析.n3窗體三元組;

from rdflib import Graph 
g = Graph() 
g.parse("demo.nt", format="nt") 

但我不確定如何解析這些四倍。

我的意圖是解析和提取有關特定ID的所有信息。學生和教師的id可以相同。

我該如何使用RDFLib來處理這些四元組並將其用於基於id的聚合?

來自實例.ttl文件片段:

#@ <id1> 
<Alice> <USA> <12345> 

#@ <id1> 
<Jane> <France> <78900> 
+0

是在問題中引用的一樣一個由標籤所引用的'ttl'? – 2013-03-02 07:20:02

+0

什麼是TTL格式? – 2013-03-02 07:20:23

+1

我認爲它的[Turtle-Terse RDF Triple Language](http://www.w3.org/TeamSubmission/turtle/) – Abhijit 2013-03-02 07:20:58

回答

0

你可以做蛇和咖啡表明,只有換行功能(或代碼)與產量語句的循環。這會創建一個生成器,可以迭代地調用該生成器來即時創建下一行的字典。假設你打算寫這些爲csv,例如,使用蛇parse_to_dict:

import re 
import csv 

writer = csv.DictWriter(open(outfile, "wb"), fieldnames=["id", "name", "address", "phone"]) 
# or whatever 

您可以創建一個發電機作爲函數或內嵌的理解:

def dict_generator(lines): 
    for line in lines: 
     yield parse_to_dict(line) 

--or -

dict_generator = (parse_to_dict(line) for line in lines) 

這幾乎是等價的。在這一點上,你可以通過調用dict_generator.next()得到一個字典解析的行,並且你會一次神奇地得到一個 - 沒有額外的RAM抖動涉及。

如果您有16個演唱會的原始數據,您可以考慮製作一臺發電機來吸引線路。他們真的很有用。

從SO發電機和一些文檔更多信息: What can you use Python generator functions for? http://wiki.python.org/moin/Generators

+0

蛇和咖啡..parse_to_dict行不在那裏,我忘了那行意圖做什麼 – 2013-03-02 08:09:09

6

TurtleNotation 3語法的一個子集,以便rdflib應該能夠使用format='n3'解析它。 檢查rdflib是否保留評論(id s在您的示例中的評論(#...)中指定)。如果不是,如圖所示在你的榜樣,那麼你可以手動解析它的輸入格式很簡單:

import re 
from collections import namedtuple 
from itertools import takewhile 

Entry = namedtuple('Entry', 'id name address phone') 

def get_entries(path): 
    with open(path) as file: 
     # an entry starts with `#@` line and ends with a blank line 
     for line in file: 
      if line.startswith('#@'): 
       buf = [line] 
       buf.extend(takewhile(str.strip, file)) # read until blank line 
       yield Entry(*re.findall(r'<([^>]+)>', ''.join(buf))) 

print("\n".join(map(str, get_entries('example.ttl')))) 

輸出:

Entry(id='id1', name='Alice', address='USA', phone='12345') 
Entry(id='id1', name='Jane', address='France', phone='78900') 

將條目保存到數據庫:

import sqlite3 

with sqlite3.connect('example.db') as conn: 
    conn.execute('''CREATE TABLE IF NOT EXISTS entries 
      (id text, name text, address text, phone text)''') 
    conn.executemany('INSERT INTO entries VALUES (?,?,?,?)', 
        get_entries('example.ttl')) 

若要在Python中進行一些後處理,請按組編號:

import sqlite3 
from itertools import groupby 
from operator import itemgetter 

with sqlite3.connect('example.db') as c: 
    rows = c.execute('SELECT * FROM entries ORDER BY id LIMIT ?', (10,)) 
    for id, group in groupby(rows, key=itemgetter(0)): 
     print("%s:\n\t%s" % (id, "\n\t".join(map(str, group)))) 

輸出:

id1: 
    ('id1', 'Alice', 'USA', '12345') 
    ('id1', 'Jane', 'France', '78900')