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'重写整个文本文件,它将被重写。而且我应该如何删除它。我知道我在文件中插入文字的方式也是错误的。请帮我解决一下这个。
答案 0 :(得分:1)
正如@Vaibhav Desai所提到的,你可以定期写整本字典。例如,考虑编写序列化对象的pickle
module:
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部分可以帮助您找到最适合您问题的模块。
答案 1 :(得分:0)
你是对的,将这些值存储在一个简单的文本文件中是个坏主意。如果要更新一个单词,则必须重写整个文件。而对于搜索单个单词,您最终可能会搜索文件中的每个单词。
有一些专门为字典设计的数据结构(例如,Trie树),但假设你的字典不是很大,你可以使用sqlite数据库。 Python有sqlite3库。查看documentation了解详情。
答案 2 :(得分:0)
首先,每次在字典中发生更新或插入时写入磁盘都是一个非常糟糕的主意 - 您的程序只会耗费太多的I / O.因此,更简单的方法是将键值对存储在字典中,并在程序退出时或以某个固定的时间间隔将其保存到磁盘。
此外,如果您不热衷于以人类可读的形式(例如纯文本文件)将数据存储在磁盘上;您可以考虑使用内置的pickle模块,如here所示,将数据保存到定义良好的磁盘位置。因此,在程序启动期间,您可以从这个定义明确的位置读取并将数据“解开”回到字典对象中。通过这种方式,您可以单独使用字典对象,甚至可以轻松完成查找项目或删除项目等操作。请参阅以下解决您的要求的脚本。我已经使用 pickle 模块来持久保存到文件中,您可能希望将其转储到文本文件中并作为单独的练习从中读取。此外,我还没有使用后缀 2 来介绍我的功能,例如 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()