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()

我是 python 新手。我已经尝试了好几天才能得到这个。但仍然没有找到解决方案。事情是最初我做了一个简单的字典程序来存储单词及其含义。然后我想我应该永久存储这些单词。我有点尝试将单词存储在文本文件中并显示它。但我不知道如何在文本文件中搜索单词。假设我找到了这个词,我想更新它的意思。那我该怎么做。因为如果我使用'w'重写整个文本文件,它将被重写。还有我应该如何删除它。我知道我在文件文本中插入单词的方式也是错误的。请帮我解决一下这个。

4

3 回答 3

1

正如@Vaibhav Desai 提到的,您可以定期编写整个字典。例如考虑写入序列化对象的pickle 模块:

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定期调用,或者要求显式调用它。

正如其他人所建议的那样,如果您需要对字典进行大量写入,则最好使用sqlite3 module,将 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部分可以帮助您找到最适合您的问题的模块。

于 2013-10-02T11:39:37.677 回答
0

首先,每次对字典进行更新或插入时都写入磁盘是一个非常糟糕的主意——您的程序只是消耗了太多的 I/O。因此,更简单的方法是将键值对存储在字典中,并在程序退出时或在某个固定时间间隔将其保存到磁盘。

此外,如果您不希望以人类可读的形式(例如纯文本文件)将数据存储在磁盘上;您可以考虑使用此处所示的内置 pickle 模块将数据保存到明确定义的磁盘位置。因此,在程序启动期间,您可以从这个定义明确的位置读取数据并将数据“取消腌制”回字典对象。这样您就可以单独使用字典对象,甚至可以轻松完成查找项目或删除项目等操作。请参考以下脚本来解决您的要求。我使用了pickle模块来持久化文件,您可能希望将其转储到文本文件并作为单独的练习从中读取。另外,我还没有介绍我的后缀为2的函数,例如insert2以便您可以将您的功能与我的功能进行比较并了解差异:

另一件事-您的程序中有错误;您应该使用 raw_input() 来读取用户输入而不是 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()
于 2013-10-02T11:48:02.703 回答
0

你是对的,将这些值存储在一个简单的文本文件中是一个坏主意。如果要更新一个单词,则必须重写整个文件。对于搜索单个单词,您最终可能会搜索文件中的每个单词。

有一些专门为字典设计的数据结构(例如,Trie 树),但假设你的字典不是真的很大,你可以使用 sqlite 数据库。Python 有 sqlite3 库。查看文档以获取更多信息。

于 2013-10-02T11:20:28.620 回答