2011-11-02 116 views
2

使用Python我設法讓自己成爲一種術語和它們的含義的詞典,它相當大 - x00,000項目(現在無法估計,因爲它們按首字母存儲在多個文件中)。如果它的事項是Python字典對象,與主要string和值的元組,然後將此元組由字符串或列表對象的數據庫字典存儲推薦

dict{word, (attribute, 
      kind, 
      [meanings], 
      [examples], 
      [connections] 
      ) 
    } 


文件醃製字典對象的這種結構。

現在我打算把它們放在sqlite3數據庫中,因爲它很容易使用Python。在我這樣做之前,我曾想過要求建議,如果sqlite3是不錯的選擇,因爲我以前從未做過任何真正的數據庫任務。

我知道答案取決於我想用這些數據做什麼(除了它的結構),但是讓我們說我只是希望它在本地存儲在一個地方(文件)並且合理易於訪問(查詢)並可能進行改造。

+0

ZODB是一個對象數據庫,它是在Zope框架中執行和驗證的 – aitchnyu

回答

0

是的,我已經使用sqlite3這種事情。字典值必須首先被醃製:

import sqlite3 
import pickle 
import collections 

class DBDict(collections.MutableMapping): 
    'Database driven dictlike object (with non-persistent in-memory option).' 

    def __init__(self, db_filename=':memory:', **kwds): 
     self.db = sqlite3.connect(db_filename) 
     self.db.text_factory = str 
     try: 
      self.db.execute('CREATE TABLE dict (key text PRIMARY KEY, value text)') 
      self.db.execute('CREATE INDEX key ON dict (key)') 
      self.db.commit() 
     except sqlite3.OperationalError: 
      pass    # DB already exists 
     self.update(kwds) 

    def __setitem__(self, key, value): 
     if key in self: 
      del self[key] 
     value = pickle.dumps(value) 
     self.db.execute('INSERT INTO dict VALUES (?, ?)', (key, value)) 
     self.db.commit() 

    def __getitem__(self, key): 
     cursor = self.db.execute('SELECT value FROM dict WHERE key = (?)', (key,)) 
     result = cursor.fetchone() 
     if result is None: 
      raise KeyError(key) 
     return pickle.loads(result[0]) 

    def __delitem__(self, key): 
     if key not in self: 
      raise KeyError(key) 
     self.db.execute('DELETE FROM dict WHERE key = (?)', (key,)) 
     self.db.commit() 

    def __iter__(self): 
     return iter([row[0] for row in self.db.execute('SELECT key FROM dict')]) 

    def __repr__(self): 
     list_of_str = ['%r: %r' % pair for pair in self.items()] 
     return '{' + ', '.join(list_of_str) + '}' 

    def __len__(self): 
     return len(list(iter(self))) 



>>> d = DBDict(raymond='red', rachel='blue') 
>>> d 
{'rachel': 'blue', 'raymond': 'red'} 
>>> d['critter'] = ('xyz', [1,2,3]) 
>>> d['critter'] 
('xyz', [1, 2, 3]) 
>>> len(d) 
3 
>>> list(d) 
['rachel', 'raymond', 'critter'] 
>>> d.keys() 
['rachel', 'raymond', 'critter'] 
>>> d.items() 
[('rachel', 'blue'), ('raymond', 'red'), ('critter', ('xyz', [1, 2, 3]))] 
>>> d.values() 
['blue', 'red', ('xyz', [1, 2, 3])] 

以上將使您的數據庫保持在單個文件中。您可以像普通的Python字典一樣瀏覽對象。由於這些值在單個字段中進行了pickle,因此sqlite不會爲您提供任何其他查詢選項。其他平面文件存儲將具有類似的限制。如果您需要編寫遍歷分層結構的查詢,請考慮使用NoSQL數據庫。

+0

爲什麼不擱置? – agf

+0

謝謝你的答案。我不知道爲什麼我使用sqlite3質疑,但這也許是因爲我從來沒有做過db,如前所述。我甚至不知道Python SPL中的shelve模塊,但是sqlite3可以通過CLI或者通過GUI訪問,並且可以通過一個簡單的代碼片段作爲Python對象的選擇,我只是創建了這個db文件。感謝雷蒙德爲您的額外片段作爲一種可能性 – theta