制作英文学习词典。编写程序制作英文学习词典,词典有 3 个基本功能:添加、
查询和退出。程序读取源文件路径下的 txt 格式词典文件,若没有就创建一个。
词典文件存储方式为“英文单词 中文单词”,每行仅有一对中英释义。程序会根据
用户的选择进入相应的功能模块,并显示相应的操作提示。当添加的单词已存在
时,显示“该单词已添加到字典库”;当查询的单词不存在时,显示“字典库中未找
到这个单词”。用户输入其他选项时,提示“输入有误”。
可以参考下这个
#英文字典
def oppendict():
dir = 'mydict.txt'
dicts = {}
tf=open(dir,'r+')
print('本字典已有的内容:')
for item in tf:
k,v=tuple(item.replace('\n','').split(':'))
print(k,v)
dicts[k]=v
tf.close()
return dicts
dicts=oppendict()
#查字典
def lookup():
quest=input("请输入要查询的单词")
result=dicts.get(quest,"字典库中未找到这个单词")
print('该单词的解释为:'+result+'\n')
#插入新单词
def inserts():
word = input("请输入要插入的单词:")
if dicts.get(word):
print('该单词已添加到字典库'+'\n')
else:
explain=input("请输入该单词的解释:")
dicts[word]=explain
#更新单词解释
def renew():
word = input('请输入需要更新解释的单词:')
explain=input("请输入单词的新解释:")
dicts[word]=explain
#删除
def deldict():
word = input('请输入删除的单词:')
if dicts.get(word):
del dicts[word]
else:
print('没有这个单词')
print(dicts)
#存档
def savedict():
dir='mydict.txt'
tf = open(dir,'w+')
for item in dicts.items():
tf.write(':'.join(item) + '\n' )
tf.close()
def meun():
meuns=['1.查询','2.新增','3.更新','4.删除','5.退出']
funcname = ['','lookup','inserts' ,'renew' , 'deldict']
while True:
print('\n'.join(meuns))
trs = eval(input('请用数字选择:'))
if trs==5:
break
elif trs in range(1,5):
eval(funcname[trs])()
else:
print('输入有误'+'\n')
if __name__=='__main__':
print('欢迎使用本字典'.center(20,'='))
meun()
print('再见'.center(20,'='))
savedict()
dicts = oppendict()
你题目的解答代码如下:
#-*- coding:utf-8 -*-
class System():
def __init__(self):
self.data = {}
self.load()
while True:
print("********** 菜单 ***********")
print("\t1.查询")
print("\t2.添加")
print("\t3.删除")
print("\t4.保存并退出")
print("****************************")
s = input("请输入1-4选择功能并按回车:")
if s=="1":
self.inquire()
elif s=="2":
self.add()
elif s=="3":
self.delete()
elif s=="4":
self.save()
print('保存并退出字典')
break
else:
print('输入有误')
def load(self):
try:
with open("dictdata.txt","r", encoding='utf-8') as f:
for s in f.readlines():
k,v = s.strip().split(" ",1)
self.data[k] = v
except IOError:
self.data = {}
def save(self):
with open("dictdata.txt","w", encoding='utf-8') as f:
for k,v in self.data.items():
f.write(f'{k} {v}\n')
def inquire(self):
s = input("输入要查询的单词:")
if s in self.data.keys():
print("单词:",s)
print("解释:",self.data[s])
else:
print('字典库中未找到这个单词')
def add(self):
s = input("输入要添加的单词:")
if s in self.data.keys():
print("该单词已添加到字典库")
else:
self.data[s] = input("输入中文解释:")
def delete(self):
s = input("输入要删除的单词:")
if s in self.data.keys():
del self.data[s]
print("删除成功")
else:
print('字典库中未找到这个单词')
sys = System()
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
def search(): # 查找
try:
fo = open("dictionary.txt", 'r')
except IOError:
fo = open("dictionary.txt", 'w+')
word2 = input("请输入查找的单词:")
ls = []
judge = "not"
for line in fo:
line = line.replace("\n", "")
ls = line.split("\n")
lsn = ""
judge = "yes"
for s in ls:
lsn += "{}".format(s)
if word2 in lsn:
print(lsn[:])
word2 = "yes"
break
else:
judge = "not"
if judge == "not":
print("字典库中未找到这个单词")
fo.close()
# -----------------------------------------------------------------------------------
def add():
ww = input("请输入你要添加的单词:")
flag = 0
dic = {}
try:
f = open("dictionary.txt", 'r')
except IOError:
f = open("dictionary.txt", 'w+')
for line in f.readlines():
line = line.replace("\n", "")
line = list(line.split(","))
key = line[0]
coment = line[1:]
dic[key] = coment
if ww in dic.keys():
f.close()
flag = 1
print("输入的单词已经存在!")
break
else:
f.close()
if flag != 1: # 如果输入的单词不存在,则进行汉语意思的输入,若有多个意思,则用英文逗号隔开
fw = open("dictionary.txt", 'a')
mean = input("若有多个意思,用英文逗号隔开:")
fw.write(ww+':'+mean+'\n')
fw.close()
if __name__ == '__main__':
print("请选择功能:\n1.查询\n2.添加\n3.退出")
n = int(input())
if n == 1:
search()
elif n == 2:
add()
elif n == 3:
exit()
else:
print("输入有误")
import os
def add_word(): #添加单词
words_list = [] #用来暂时存放单词
word = input("请输入你要添加的单词和解释(用一个空格键隔开中英文):")
with open('单词本.txt','a+') as f:
f.seek(0) #光标移到文件开头,以备检查单词
words = f.readlines() #将txt每行元素读取成列表形式赋值给words
for element in words:
element = element.split(' ') #用空格将中英文切分
words_list.append(element[0]) #后面用来比较单词是否存在
sub_word = word.split(' ')
if sub_word[0] in words_list:
print("该单词已添加到字典库")
else:
f.seek(2) #光标移到文件开头,以备添加单词
f.write(word)
f.write('\n') #写完换行,一行一行写
def query(): #查询单词
words_list = [] #用来暂时存放单词
meaning_list = [] #用来暂时存放释义
word = input("请输入你要查询的单词:")
with open('单词本.txt','r') as f:
words = f.readlines()
for element in words:
element = element.split(' ')
words_list.append(element[0])
meaning_list.append(element[-1]) #后面用来返回单词释义
if word in words_list:
index = words_list.index(word) #找到要查询的单词在暂存列表里的索引
print("含义:",meaning_list[index]) #for语句中对应顺序存放中英文,从而可以根据英文索引找到对应中文索引,从而得到索引下的元素
else:
print("字典库中未找到这个单词")
menu_choice = [1, 2, 3]
print("功能选择:")
print("1、添加")
print("2、查询")
print("3、退出")
menu = eval(input("您的选择是(请输入数字,例如:1):"))
flag = menu in menu_choice #标识符
while not flag:
print("输入有误")
menu = eval(input("请重新输入:"))
flag = menu in menu_choice #重新赋值
while flag:
if os.path.exists('单词本.txt'):
if menu==1:
add_word()
elif menu==2:
query()
else:
exit()
else:
with open('单词本.txt','w'):
pass #创建单词本
menu = eval(input("您的选择是(请输入数字,例如:1):"))
flag = menu in menu_choice #最后两行是为了多次使用,直到你想要退出