简体   繁体   English

我的词典程序需要帮助

[英]I need Help in My Dictionary program

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

I am new to python. 我是python的新手。 I have been trying for days to get this. 我已经尝试了好几天了。 But still no solution found. 但是仍然找不到解决方案。 The thing is initially i made a simple dictionary program which stores words and their meanings. 最初,我制作了一个简单的词典程序来存储单词及其含义。 Then i thought i should store the words permanently. 然后我认为我应该将这些单词永久存储。 I have somewhat tried to store the words in a text file and displaying it. 我已经尝试过将单词存储在文本文件中并显示出来。 But i am not getting how to search the word in the text file. 但是我没有得到如何在文本文件中搜索单词的信息。 And suppose i find the word and i want to update its meaning. 假设我找到了这个词,并且想更新它的意思。 So how should i do it. 所以我应该怎么做。 Cause if i use the 'w' to rewrite it the whole text file and it will get rewritten. 原因是如果我使用“ w”重写整个文本文件,它将被重写。 And also how should i delete it. 还有我应该如何删除它。 I know the way I have inserted the word in the text in the file is also wrong. 我知道我在文件中的文本中插入单词的方式也是错误的。 Please help me with this. 请帮我解决一下这个。

As @Vaibhav Desai mentionned, you can write the entire dictionary at regular intervals. 正如@Vaibhav Desai所提到的,您可以定期编写整个字典。 Consider for instance the pickle module which writes serialized objects: 考虑一下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()

    ...

This will rewrite the entire dictionary to the disk every time you make a modification, which might make sense for some cases, but is probably not the most efficient. 每次进行修改时,这会将整个字典重写到磁盘上,这在某些情况下可能是有道理的,但可能不是最有效的。 You can also make a more clever mechanism which calls _writeback at regular intervals, or require it to be called explicitly. 您还可以创建一种更聪明的机制,该机制定期调用_writeback或要求显式调用它。

As others have suggested, if you require a lot of writes to the dictionary, you would be better off using the sqlite3 module , to have a SQL table as your dictionary: 正如其他人所建议的那样,如果您需要对字典进行大量写操作,那么最好使用sqlite3 模块 ,将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

    ...

This is just an example, you can for instance maintain the connection open and require it to be closed explicitly, or queue your queries... But it should give you a rough idea of how you can persist data to the disk. 这只是一个示例,例如,您可以保持连接打开并要求其显式关闭,或者将查询排队...但是,这应该使您大致了解如何将数据持久化到磁盘。

In general, the Data Persistence section of the Python documentation can help you to find the most appropriated module for your problem. 通常,Python文档的“ 数据持久性”部分可以帮助您找到最适合您问题的模块。

You are right, storing these values in a simple text file is a bad idea. 没错,将这些值存储在简单的文本文件中是个坏主意。 If you want to update one word, you have to rewrite the whole file. 如果要更新一个单词,则必须重写整个文件。 And for searching a single word you might end up with searching every word in the file. 对于搜索单个单词,您可能最终会搜索文件中的每个单词。

There are some data structures specially designed for dictionary (for example, Trie tree), but assuming your dictionary is not really really big, you can use a sqlite database. 有一些专门为字典设计的数据结构(例如Trie树),但是如果您的字典不是真的很大,则可以使用sqlite数据库。 Python has sqlite3 library. Python具有sqlite3库。 Check the documentation for more info. 查看文档以获取更多信息。

First of all, writing to the disk every time an update or insert happens to the dictionary is a very bad idea - your program simply uses up too much I/O. 首先,每次对字典进行更新或插入时都将磁盘写入磁盘是一个非常糟糕的主意-您的程序只会占用过多的I / O。 Hence, an easier way to do it would be to store the key-value pairs within a dictionary and save it to the disk either when the program quits or at some regular time interval. 因此,一种更简单的方法是将键值对存储在字典中,并在程序退出时或以某个规则的时间间隔将其保存到磁盘中。

Also, in case you are not keen on storing data on the disk in a human readable form (such as aa plain text file); 另外,如果您不希望以人类可读的形式(例如纯文本文件)将数据存储在磁盘上,请执行以下操作: you can consider using the built-in pickle module as shown here to save the data to a well defined disk location. 如图所示,你可以考虑使用内置的泡菜模块这里将数据保存到一个定义良好的磁盘位置。 Hence during program start-up you can read from this well-defined location and "un-pickle" the data back into a dictionary object. 因此,在程序启动期间,您可以从定义明确的位置读取数据,并将数据“解钉”回字典对象中。 This way you can work solely with the dictionary object and even operations such as finding an item or deleting an item can be done easily.Please refer to the below script that solves your requirement. 这样,您就可以只使用字典对象,甚至可以轻松完成查找项目或删除项目之类的操作。请参考以下满足您要求的脚本。 I have used the pickle module to persist to the file, you may want to dump it to a text file and read from it as a separate exercise. 我已经使用了pickle模块将其持久保存到文件中,您可能希望将其转储到文本文件中并作为一个单独的练习从中读取。 Also, I have not introduced my function with the suffix 2 for eg insert2 so that you can compare your function with mine and understand the differences: 另外,我还没有介绍带有后缀2的函数,例如insert2,因此您可以将其与我的函数进行比较并了解它们的区别:

One another thing - There was bug in your program; 另一件事-您的程序中存在错误; you should use raw_input() to read in user input and not input() 您应该使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM