栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python制作英文学习词典

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python制作英文学习词典

编写程序制作英文学习词典,实现3个基本功能。添加,查询和退出。

以下是该词典的Python代码:

dict = {}
digits = '0123456789'
path = 'dict.txt'

def readFile(path, arg):

    try:
        file = open(path,arg,encoding = "utf-8")
    except:
        file = open(path,'w',encoding= "utf-8")

    return file
def readWords():
    file = readFile(path, 'r')
    while True:
        line = file.readline()
        if not line:
            break
        word = line.split(' ',2)
        dict[word[0]] = word[1][:-1]
    file.close()

def writeFile(word,dsp):
    file = readFile(path,'a')
    file.write('{} {}n'.format(word, dsp))
    file.close()

def modifyFile(word, dsp):
    file = readFile(path,'r')
    line = file.readlines()
    flen = len(line) -1
    for i in range(flen):
        if word in line[i]:
            file.close()
            line[i] = '{} {}n'.format(word, dsp)
            file = readFile(path,'w')
            file.writelines(line)
            break
    file.close()

def editMode():
    print('*'*50)
    print('*'*50)
    while True:
        word = input("(按数字键退出)请输入想添加或修改的单词")
        if word in digits:
            print('*'*50)
            print('*'*50)
            return
        try:
            print("该单词已经存在,当前解释是:{}".format(dict[word]))
        except:
            print('您添加的是一个新单词')
        print("-----------------------")
        description = input("输入解释:n")
        try:
            dict[word] += ',%s'%description
            modifyFile(word, dict[word])
        except KeyError:
            dict[word] = '%s'%description
            writeFile(word,dict[word])
        print('----------------添加完成---------------')

def searchMode():
    print('*'*50)
    print('*'*50)
    while True:
        word = input("(按数字键退出)想查的单词:")
        if word in digits:
            print('*'*50)
            print('*'*50)
            return
        print("-----------------------------------")
        try:
            print(dict[word])
        except KeyError:
            print('对不起,这个单词未收录')

        print("------------------------------------------")

def interface():
    readWords()
    def switch(option):
        funcdic={
            1:lambda :searchMode(),
            2:lambda :editMode(),
            3:lambda :exit()
        }
        return funcdic[option]()
    while True:
        print("-------------欢迎使用-------------")
        print("1.查询单词n2.添加单词n3.退出n")
        option =int(input("请输入选择:"))
        switch(option)

interface()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/317358.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号