2013-10-02 46 views
1
def createdictionary(): 
    mydictionary = dict() 
    mydictionary['Computer']='Computer is an electronic machine.' 
    mydictionary['RAM']='Random Access Memory' 
    return mydictionary 

def insert(dictionary): 
    print("Enter the keyword you want to insert in the dictionary: ") 
    key=input() 
    print("Enter its meaning") 
    meaning=input() 
    dictionary[key]=meaning 
    f = open('dict_bckup.txt','a') 
    f.write(key) 
    f.write('=') 
    f.write(meaning) 
    f.write(';\n') 
    f.close() 
    print("Do you want to insert again? y/n") 
    ans=input() 
    if (ans == 'y' or ans=='Y'): 
     insert(dictionary) 

def display(dictionary): 
    print("The contents of the dictionary are : ") 
    f = open('dict_bckup.txt','r') 
    print(f.read()) 
    f.close() 

def update(dictionary): 
    print("Enter the word whose meaning you want to update") 
    key=input() 
    #i want to edit the meaning of the key in the text file 
    f = open('dict_bckup.txt','w') 
    if key in dictionary: 
     print(dictionary[key]) 
     print("Enter its new meaning: ") 
     new=input() 
     dictionary[key]=new 
    else: 
     print("Word not found! ") 
    print("Do you want to update again? y/n") 
    ans=input() 
    if (ans=='y' or ans=='Y'): 
     update(dictionary) 

def search(dictionary): 
    print("Enter the word you want to search: ") 
    word=input() 
    if word in dictionary: 
     print(dictionary[word]) 

else: 
    print("Word not found! ") 
print("Do you want to search again? y/n") 
ans=input() 
if(ans=='y' or ans=='Y'): 
    search(dictionary) 


def delete(dictionary): 
    print("Enter the word you want to delete: ") 
    word=input() 
    if word in dictionary: 
     del dictionary[word] 
     print(dictionary) 
    else: 
     print("Word not found!") 

    print("Do you want to delete again? y/n ") 
    ans=input() 
    if (ans == 'y' or ans == 'Y'): 
     delete(dictionary) 

def sort(dictionary): 
    for key in sorted(dictionary): 
     print(" %s: %s "%(key,(dictionary[key]))) 


def main(): 
    dictionary=createdictionary() 
    while True: 

     print("""    Menu 
      1)Insert 
      2)Delete 
      3)Display Whole Dictionary 
      4)Search 
      5)Update Meaning 
      6)Sort 
      7)Exit 
      Enter the number to select the coressponding field """) 

     ch=int(input()) 

     if(ch==1): 
      insert(dictionary) 

     if(ch==2): 
      delete(dictionary) 

     if(ch==3): 
      display(dictionary) 

     if(ch==4): 
      search(dictionary) 

     if(ch==5): 
      update(dictionary) 

     if(ch==6): 
      sort(dictionary) 

     if(ch==7):           
      break 


main() 

我是新來的蟒蛇。我一直在努力幾天才能得到這個。但仍然沒有找到解決辦法。事情最初我做了一個簡單的字典程序,它存儲了單詞和它們的含義。然後我想我應該永久保存這些詞。我有些嘗試將文字存儲在文本文件中並顯示它。但我沒有得到如何搜索文本文件中的單詞。假設我找到了這個詞,我想更新它的意思。所以我應該怎麼做。因爲如果我使用'w'來重寫它的整個文本文件,它會被重寫。而且我應該如何刪除它。我知道我在文件中插入單詞的方式也是錯誤的。請幫我解決一下這個。我需要幫助在我的詞典程序

+0

,你可以在內存中緩存整個事情用的地圖使您所有的操作變得輕鬆刷新映射(重寫整個文件)定期到磁盤。順便說一句,在這個問題上可能有幾個優化。繼續閱讀。 –

+0

使用sqlite數據庫 –

回答

0

你說得對,將這些值存儲在一個簡單的文本文件中是一個壞主意。如果你想更新一個單詞,你必須重寫整個文件。而搜索單個單詞時,最終可能會搜索文件中的每個單詞。

有一些專門爲字典設計的數據結構(例如Trie樹),但假設你的字典並不真的很大,你可以使用一個sqlite數據庫。 Python有sqlite3庫。查看documentation瞭解更多信息。

1

正如@Vaibhav Desai所說,您可以定期編寫整本字典。例如考慮在picklemodule其寫入序列化對象:

import pickle 

class MyDict(object): 
    def __init__(self, f, **kwargs): 
     self.f = f 
     try: 
      # Try to read saved dictionary 
      with open(self.f, 'rb') as p: 
       self.d = pickle.load(p) 
     except: 
      # Failure: recreating 
      self.d = {} 
     self.update(kwargs) 

    def _writeback(self): 
     "Write the entire dictionary to the disk" 
     with open(self.f, 'wb') as p: 
      pickle.dump(p, self.d) 

    def update(self, d): 
     self.d.update(d) 
     self._writeback() 

    def __setitem__(self, key, value): 
     self.d[key] = value 
     self._writeback() 

    def __delitem__(self, key): 
     del self.d[key] 
     self._writeback() 

    ... 

這將改寫整個字典到磁盤每次進行修改,這可能是有意義的某些情況下的時間,但可能不是最有效的。您也可以制定一個更爲巧妙的機制,定期調用_writeback,或要求明確調用_writeback

正如其他人所建議的,如果你需要大量寫入字典,你會使用sqlite3module,有一個SQL表作爲你的字典會更好:

import sqlite3 

class MyDict(object): 
    def __init__(self, f, **kwargs): 
     self.f = f 
     try: 
      with sqlite3.connect(self.f) as conn: 
       conn.execute("CREATE TABLE dict (key text, value text)") 
     except: 
      # Table already exists 
      pass 

    def __setitem__(self, key, value): 
     with sqlite3.connect(self.f) as conn: 
      conn.execute('INSERT INTO dict VALUES (?, ?)', str(key), str(value)) 

    def __delitem__(self, key): 
     with sqlite3.connect(self.f) as conn: 
      conn.execute('DELETE FROM dict WHERE key=?', str(key)) 

    def __getitem__(self, key): 
     with sqlite3.connect(self.f) as conn: 
      key, value = conn.execute('SELECT key, value FROM dict WHERE key=?', str(key)) 
      return value 

    ... 

這只是一個例如,你可以維持連接打開,並要求它明確關閉,或排隊查詢......但它應該給你一個粗略的想法,你可以如何將數據保存到磁盤。

通常,Python文檔的Data Persistence部分可以幫助您找到最適合您問題的模塊。

0

首先,每次更新或插入字典時寫入磁盤是一個非常糟糕的主意 - 您的程序只是用盡了太多的I/O。因此,更簡單的方法是將鍵值對存儲在字典中,並在程序退出時或以某個固定的時間間隔將其保存到磁盤中。另外,如果你不喜歡以人類可讀形式(例如純文本文件)將數據存儲在磁盤上,您可以考慮使用如here所示的內置泡菜模塊將數據保存到定義良好的磁盤位置。因此,在程序啓動時,您可以從這個明確定義的位置讀取數據,並將數據「清理」回到字典對象中。這樣您就可以單獨使用字典對象,甚至可以輕鬆完成查找項目或刪除項目等操作。請參閱下面的腳本來解決您的需求。我已經使用pickle模塊來保存該文件,您可能希望將其轉儲到文本文件並作爲單獨的練習讀取它。另外,我還沒有介紹我的功能,例如後綴爲,例如,insert2,以便您可以將您的功能與我的功能進行比較並瞭解其差異:

另一件事 - 您的程序中存在錯誤;你應該使用的raw_input()如果字典不是太大讀取用戶輸入和不輸入()

import pickle 
import os 

def createdictionary(): 
    mydictionary = dict() 
    mydictionary['Computer']='Computer is an electronic machine.' 
    mydictionary['RAM']='Random Access Memory' 
    return mydictionary 

#create a dictionary from a dump file if one exists. Else create a new one in memory.  
def createdictionary2(): 

    if os.path.exists('dict.p'): 
     mydictionary = pickle.load(open('dict.p', 'rb')) 
     return mydictionary 

    mydictionary = dict() 
    mydictionary['Computer']='Computer is an electronic machine.' 
    mydictionary['RAM']='Random Access Memory' 
    return mydictionary 

def insert(dictionary): 
    print("Enter the keyword you want to insert in the dictionary: ") 
    key=raw_input() 
    print("Enter its meaning") 
    meaning=raw_input() 
    dictionary[key]=meaning 
    f = open('dict_bckup.txt','a') 
    f.write(key) 
    f.write('=') 
    f.write(meaning) 
    f.write(';\n') 
    f.close() 
    print("Do you want to insert again? y/n") 
    ans=raw_input() 
    if (ans == 'y' or ans=='Y'): 
     insert(dictionary) 

#custom method that simply updates the in-memory dictionary 
def insert2(dictionary): 
    print("Enter the keyword you want to insert in the dictionary: ") 
    key=raw_input() 
    print("Enter its meaning") 
    meaning=raw_input() 
    dictionary[key]=meaning 

    print("Do you want to insert again? y/n") 
    ans=raw_input() 
    if (ans == 'y' or ans=='Y'): 
     insert(dictionary) 



def display(dictionary): 
    print("The contents of the dictionary are : ") 
    f = open('dict_bckup.txt','r') 
    print(f.read()) 
    f.close() 

#custom display function - display the in-mmeory dictionary 
def display2(dictionary): 
    print("The contents of the dictionary are : ") 
    for key in dictionary.keys(): 
     print key + '=' + dictionary[key] 

def update(dictionary): 
    print("Enter the word whose meaning you want to update") 
    key=input() 
    #i want to edit the meaning of the key in the text file 
    f = open('dict_bckup.txt','w') 
    if key in dictionary: 
     print(dictionary[key]) 
     print("Enter its new meaning: ") 
     new=raw_input() 
     dictionary[key]=new 
    else: 
     print("Word not found! ") 
    print("Do you want to update again? y/n") 
    ans=input() 
    if (ans=='y' or ans=='Y'): 
     update(dictionary) 

#custom method that performs update of an in-memory dictionary   
def update2(dictionary): 
    print("Enter the word whose meaning you want to update") 
    key=input() 
    #i want to edit the meaning of the key in the text file 

    if key in dictionary: 
     print(dictionary[key]) 
     print("Enter its new meaning: ") 
     new=raw_input() 
     dictionary[key]=new 
    else: 
     print("Word not found! ") 
    print("Do you want to update again? y/n") 
    ans=raw_input() 
    if (ans=='y' or ans=='Y'): 
     update(dictionary) 

def search(dictionary): 
    print("Enter the word you want to search: ") 
    word=raw_input() 
    if word in dictionary: 
     print(dictionary[word]) 

    else: 
     print("Word not found! ") 
    print("Do you want to search again? y/n") 
    ans=raw_input() 
    if(ans=='y' or ans=='Y'): 
     search(dictionary) 


def delete(dictionary): 
    print("Enter the word you want to delete: ") 
    word=raw_input() 
    if word in dictionary: 
     del dictionary[word] 
     print(dictionary) 
    else: 
     print("Word not found!") 

    print("Do you want to delete again? y/n ") 
    ans=raw_input() 
    if (ans == 'y' or ans == 'Y'): 
     delete(dictionary) 

def sort(dictionary): 
    for key in sorted(dictionary): 
     print(" %s: %s "%(key,(dictionary[key]))) 

#this method will save the contents of the in-memory dictionary to a pickle file 
#of course in case the data has to be saved to a simple text file, then we can do so too 
def save(dictionary): 
    #open the dictionary in 'w' mode, truncate if it already exists 
    f = open('dict.p', 'wb') 
    pickle.dump(dictionary, f) 




def main(): 
    dictionary=createdictionary2() #call createdictionary2 instead of creatediction 
    while True: 

     print("""    Menu 
      1)Insert 
      2)Delete 
      3)Display Whole Dictionary 
      4)Search 
      5)Update Meaning 
      6)Sort 
      7)Exit 
      Enter the number to select the coressponding field """) 

     ch=int(input()) 

     if(ch==1): 
      insert2(dictionary) #call insert2 instead of insert 

     if(ch==2): 
      delete(dictionary) 

     if(ch==3): 
      display2(dictionary) #call display2 instead of display 

     if(ch==4): 
      search(dictionary) 

     if(ch==5): 
      update2(dictionary) #call update2 instead of update 

     if(ch==6): 
      sort(dictionary) 

     if(ch==7):           
      #save the dictionary before exit 
      save(dictionary); 
      break 


main()