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'重写整个文本文件,它将被重写。还有我应该如何删除它。我知道我在文件文本中插入单词的方式也是错误的。请帮我解决一下这个。