2013-10-02 45 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()