【一个简单背单词工具1.0(Python)】

说明:该程序为临摹(😀)作品,源地址背单词工具(C++)

代码的详细功能分析:

Recite 的功能

1. __init__ 方法:

- 用于初始化类的实例。
- 检查三个文件("生词本.txt"、"背词历史.log"、"历史记录.txt")是否存在,如果不存在则尝试创建。

2. insert_word 方法:

- 允许用户输入单词、词性和解释,并将其添加到"生词本.txt"文件中。
- 计算并显示写入操作所花费的时间。

3. query_all 方法:

- 读取"生词本.txt"文件中的所有记录。
- 按照特定格式打印出单词、词性和翻译的信息。
- 计算并显示查询操作所花费的时间。

4. query_by_time 方法:

- 让用户输入特定的日期(年-月-日格式)。
- 从"背词历史.log"文件中查找该日期对应的单词记录,并将其保存到临时列表中。
- 将这些记录写入"历史记录.txt"文件,然后调用 `query_history` 方法进行查询展示。

5. query_history 方法:

- 读取"历史记录.txt"文件中的记录。
- 按照特定格式打印出单词、词性和翻译的信息。
- 计算并显示查询操作所花费的时间。

6. query_exact 方法:

- 让用户选择按照单词、词性或中文解释进行精确查询的方式。
- 根据用户输入的单词,在"生词本.txt"文件中查找匹配的记录,并打印出来。
- 计算并显示查询操作所花费的时间。

7. get_num 方法:

- 计算"生词本.txt"文件中有效记录(即包含单词、词性和翻译)的数量。

8. delete_word 方法:

- 首先调用 `query_all` 方法显示所有生词。
- 让用户输入要删除的单词。
- 从"生词本.txt"文件中删除指定的单词,并更新文件内容。
- 计算并显示删除操作所花费的时间。

9. recite_word 方法:

- 从"生词本.txt"文件中读取单词、词性和翻译信息。
- 让用户进行背诵,根据用户输入判断对错。
- 背诵完成后,清空"生词本.txt"文件,并将背诵的记录添加到"背词历史.log"文件中。
- 计算并显示背诵操作所花费的时间。

10. update_log 方法:

- 打印出更新日志的相关信息。

11. run 方法:

- 显示主菜单,提供多种服务选项(添加生词、显示所有生词、精确查词、删除生词、背生词、查询背诵历史、更新日志、退出)。
- 根据用户输入的选项执行相应的方法。
- 循环显示菜单,直到用户选择退出。

主程序部分

if __name__ == "__main__": 部分:

创建 Recite 类的实例 r ,并调用 r.run 方法启动整个程序的运行。

详细代码

import time
import os

class Recite:
    def __init__(self):
        """
        初始化方法,创建必要的文件,如果文件不存在则尝试创建
        """
        filenames = ["生词本.txt", "背词历史.log", "历史记录.txt"]
        for filename in filenames:
            if not os.path.exists(filename):
                try:
                    with open(filename, 'w'):
                        pass
                except IOError:
                    print(f"创建文件{filename}失败")

    def insert_word(self):
        """
        允许用户输入单词、词性和解释,并添加到生词本文件中,计算并显示操作耗时
        """
        start_time = time.time()
        with open("生词本.txt", 'a') as file:
            if file:
                word = input("请输入要写入错题本的单词:")
                cha = input("请输入单词的词性:")
                trans = input("请输入单词的解释:")
                file.write(f"{word} {cha} {trans}\n")
                end_time = time.time()
                print(f"写入成功,总共用时{end_time - start_time} s")
            else:
                print("打开文件失败")

    def query_all(self):
        """
        读取生词本文件,展示所有单词、词性和翻译,计算并显示操作耗时
        """
        start_time = time.time()
        with open("生词本.txt", 'r') as file:
            number = 0
            print(" --------+----+---------")
            print("| 单词 | 词性 | 翻译 |")
            print(" --------+----+---------")
            for line in file:
                parts = line.strip().split()
                if len(parts) >= 3:
                    s1, s2, s3 = parts[:3]
                    number += 1
                    print(f"| {s1:8} | {s2:4} | {s3:8} |")
                    print(" --------+----+---------")
            end_time = time.time()
            print(f"总共有{number}条记录,总共用时{end_time - start_time} s")

    def query_by_time(self):
        """
        根据用户输入的时间查询背词历史文件,将结果写入历史记录文件,并调用查询历史方法展示
        """
        with open("背词历史.log", 'r+') as file:
            if file:
                time_input = input("请输入要查询的历史记录的年月日,格式为年-月-日:")
                words = []
                chas = []
                trans = []
                i = 0
                for line in file.readlines():
                    t1, t2 = line.split()
                    if t1 == time_input:
                        while True:
                            line = file.readline()
                            if not line:
                                break
                            s1, s2, s3 = line.split()
                            if s1 and s2 and s3:
                                words.append(s1)
                                chas.append(s2)
                                trans.append(s3)
                                i += 1
                            elif s1 == time_input:
                                continue
                            else:
                                break
                file.close()
                with open("历史记录.txt", 'w') as file1:
                    for j in range(i):
                        file1.write(f"{words[j]} {chas[j]} {trans[j]}\n")
                self.query_history()
            else:
                print("文件打开失败")

    def query_history(self):
        """
        读取历史记录文件,展示其中的单词、词性和翻译,计算并显示操作耗时
        """
        start_time = time.time()
        with open("历史记录.txt", 'r') as file:
            number = 0
            print(" --------+----+---------")
            print("|", end="")
            print(f"{8 *' '}单词", end="")
            print("|", end="")
            print(f"{4 *' '}词性", end="")
            print("|", end="")
            print(f"{8 *' '}翻译", end="")
            print("|")
            print(" --------+----+---------")
            for line in file.readlines():
                s1, s2, s3, s4 = line.split()
                if s1 and s2 and s3:
                    number += 1
                    print("|", end="")
                    print(f"{s1:8}", end="")
                    print("|", end="")
                    print(f"{s2:4}", end="")
                    print("|", end="")
                    print(f"{s3:8}", end="")
                    print("|")
                    print(" --------+----+---------")
            end_time = time.time()
            print(f"总共有{number}条记录,总共用时{end_time - start_time} s")

    def query_exact(self):
        """
        允许用户选择按照单词、词性或中文解释进行精确查询,并展示结果,计算并显示操作耗时
        """
        start_time = time.time()
        with open("生词本.txt", 'r') as file:
            i = int(input("1.按照单词查词\n2.按照词性查词\n3.按照中文解释查词\n请输入需要确定查词方式:"))
            word = input("请输入要查的单词:")
            number = 0
            print(" --------+----+---------")
            print("|", end="")
            print(f"{8 *' '}单词", end="")
            print("|", end="")
            print(f"{4 *' '}词性", end="")
            print("|", end="")
            print(f"{8 *' '}翻译", end="")
            print("|")
            print(" --------+----+---------")
            for line in file.readlines():
                s1, s2, s3 = line.split()
                if i == 1 and s1 == word:
                    number += 1
                    print("|", end="")
                    print(f"{s1:8}", end="")
                    print("|", end="")
                    print(f"{s2:4}", end="")
                    print("|", end="")
                    print(f"{s3:8}", end="")
                    print("|")
                    print(" --------+----+---------")
                elif i == 2 and s2 == word:
                    number += 1
                    print("|", end="")
                    print(f"{s1:8}", end="")
                    print("|", end="")
                    print(f"{s2:4}", end="")
                    print("|", end="")
                    print(f"{s3:8}", end="")
                    print("|")
                    print(" --------+----+---------")
                elif i == 3 and s3 == word:
                    number += 1
                    print("|", end="")
                    print(f"{s1:8}", end="")
                    print("|", end="")
                    print(f"{s2:4}", end="")
                    print("|", end="")
                    print(f"{s3:8}", end="")
                    print("|")
                    print(" --------+----+---------")
            end_time = time.time()
            print(f"查询成功,一共有{number}条记录,用时:{end_time - start_time} s")

    def get_num(self):
        """
        计算生词本文件中的有效记录数量(包含单词、词性和翻译)
        """
        with open("生词本.txt", 'r') as file:
            number = 0
            for line in file.readlines():
                s1, s2, s3 = line.split()
                if s1 and s2 and s3:
                    number += 1
            return number

    def delete_word(self):
        """
        展示所有生词,让用户输入要删除的单词,执行删除操作并显示结果和耗时
        """
        self.query_all()
        str_to_delete = input("请输入想要删除的单词:")
        start_time = time.time()
        updated_lines = []
        deleted = False
        with open("生词本.txt", 'r') as file:
            for line in file:
                parts = line.strip().split()
                if len(parts) >= 3 and parts[0]!= str_to_delete:
                    updated_lines.append(line)
                elif parts and parts[0] == str_to_delete:
                    deleted = True
        if deleted:
            with open("生词本.txt", 'w') as file:
                file.writelines(updated_lines)
            end_time = time.time()
            print(f"删除成功,用时:{end_time - start_time} s")
        else:
            print("未找到要删除的单词。")

    def recite_word(self):
        """
        进行生词背诵,根据用户输入判断对错,背诵完成后处理相关文件并记录背诵时间
        """
        with open("生词本.txt", 'r+') as file:
            if file:
                start_time = time.time()
                words = []
                chas = []
                trans = []
                num_of_recite = []
                i = 0
                for line in file.readlines():
                    s1, s2, s3 = line.split()
                    if s1 and s2 and s3:
                        words.append(s1)
                        chas.append(s2)
                        trans.append(s3)
                        num_of_recite.append(1)
                        i += 1
                number = i
                print(f"本次需要复习的单词数量是:{number}")
                input("按任意键继续...")
                os.system('cls')
                successful = 0
                if number == 0:
                    successful = 1
                num = 0
                while successful == 0:
                    for j in range(i):
                        if num_of_recite[j]!= 0:
                            print(f"中文意思:{trans[j]} {chas[j]}")
                            str_guess = input("请输入单词:")
                            if str_guess == words[j]:
                                print("正确!")
                                num_of_recite[j] -= 1
                                input("按任意键继续...")
                                os.system('cls')
                                num += 1
                                if num == number:
                                    successful = 1
                            else:
                                print(f"错误,正确答案是:{words[j]}")
                                num_of_recite[j] += 1
                                input("按任意键继续...")
                                os.system('cls')
                end_time = time.time()
                print(f"恭喜你背完啦~~,用时:{end_time - start_time} s")
                file.close()
                file = open("生词本.txt", 'w')
                file.close()
                with open("背词历史.log", 'a') as file1:
                    file1.write(time.strftime("%Y-%m-%d %H:%M:%S") + '\n')
                    for j in range(i):
                        file1.write(f"{words[j]} {chas[j]} {trans[j]}\n")
            else:
                print("生词表为空,先加入生词再背诵吧")

    def update_log(self):
        """
        打印更新日志的相关信息
        """
        print("新增的内容:")
        print("1.新增背词功能,在背诵完生词后生词会自动从生词表删除,并且添加到背词历史中")
        print("2.新增历史生词查询功能,可以根据当天的年与日查询背诵完的生词")

    def run(self):
        """
        主运行方法,展示菜单,根据用户输入执行相应的操作,并循环等待用户输入
        """
        print("------------------------------")
        print("|欢迎使用大家一起背单词      |")
        print("|1.添加生词                  |")
        print("|2.显示所有生词              |")
        print("|3.精确查词                  |")
        print("|4.删除生词表中的词          |")
        print("|5.背生词                    |")
        print("|6.查询背诵历史              |")
        print("|7.更新日志                  |")
        print("|8.退出                      |")
        print("------------------------------")
        print("请输入需要服务的序号:")
        i = int(input())
        while i!= 8:
            if i == 1:
                os.system('cls')
                self.insert_word()
            elif i == 2:
                os.system('cls')
                self.query_all()
            elif i == 3:
                os.system('cls')
                self.query_exact()
            elif i == 4:
                os.system('cls')
                self.delete_word()
            elif i == 5:
                os.system('cls')
                self.recite_word()
            elif i == 6:
                os.system('cls')
                self.query_by_time()
            elif i == 7:
                os.system('cls')
                self.update_log()
            elif i == 8:
                break
            else:
                print("对应数字的服务不存在,请重新输入")
            input("按任意键继续...")
            os.system('cls')
            print("------------------------------")
            print("|欢迎使用大家一起背单词      |")
            print("|1.添加生词                  |")
            print("|2.显示所有生词              |")
            print("|3.精确查词                  |")
            print("|4.删除生词表中的词          |")
            print("|5.背生词                    |")
            print("|6.查询背诵历史              |")
            print("|7.更新日志                  |")
            print("|8.退出                      |")
            print("------------------------------")
            print("请输入需要服务的序号:")
            i = int(input())


if __name__ == "__main__":
    r = Recite()
    r.run()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值