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'來重寫它的整個文本文件,它會被重寫。而且我應該如何刪除它。我知道我在文件中插入單詞的方式也是錯誤的。請幫我解決一下這個。我需要幫助在我的詞典程序
,你可以在內存中緩存整個事情用的地圖使您所有的操作變得輕鬆刷新映射(重寫整個文件)定期到磁盤。順便說一句,在這個問題上可能有幾個優化。繼續閱讀。 –
使用sqlite數據庫 –