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

Python第7章字典练习题7.6

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

Python第7章字典练习题7.6

修改程序练习题7.5的程序,使其能够对单词添加多重释义,不同释义用逗号分开.

下面是源代码

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()

下面是对上面问题的解析

拿到这类,比较繁琐的练习题:

首先,列出程序的实现目标,比如在上面的问题中,我总共要实现2个功能,增和查。

需要怎么实现呢?先需要对文件进行操作,那么对于整个题目来说,我还需要跟用户进行显示。

因此简单的分为四个板块

文件操作,增添,查找,交互

分别对应上面的代码块。

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

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

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