有趣的python程序Part1:如何根据记忆曲线使用python编写一个单词记忆默写程序

目录

前言

1. 数据管理模块

 2. 记忆算法实现

3. 持久化存储

 4. 用户界面实现

5.整合与测试


前言

        此篇文章为“有趣的python程序”专栏的第一篇文章,本专栏致力于分享一些有趣的编程作品,如果能够使您产生兴趣,不妨来动手改编使之成为更好的工具吧!若是能够帮助到您,在下不胜荣幸!

我们先来确定一下单词记忆程序的功能框架,它需要具有以下功能:

- 基于记忆曲线(艾宾浩斯遗忘曲线)安排单词复习
- 记录用户对单词的掌握情况
- 提供学习和测试两种模式
- 持久化保存学习数据


故此我们可以将程序分为几个核心部分:
- **数据管理**:存储单词及其记忆状态
- **记忆算法**:计算下次复习时间
- **用户界面**:与用户交互的界面
- **持久化存储**:保存学习进度

## 第二阶段:分模块实现

1. 数据管理模块

先来看以下代码:

import datetime
from collections import defaultdictclass WordMemorySystem:def __init__(self):# 使用字典存储所有单词数据self.word_data = defaultdict(dict)# 记忆曲线间隔 (天)self.review_intervals = [1, 2, 4, 7, 15, 30, 60, 90]def add_word(self, word, meaning, example=""):"""添加新单词"""today = datetime.date.today()if word not in self.word_data:self.word_data[word] = {'meaning': meaning,'example': example,'added_date': today,'last_reviewed': today,'next_review': today + datetime.timedelta(days=self.review_intervals[0]),'review_count': 0,'correct_count': 0,'incorrect_count': 0}

我们在这里使用列表来储存记忆曲线的节点,这样当我们核对各个单词的背诵时间时就可以与列表里的时间相比对,我们来详细分析这一句。

'next_review': today + datetime.timedelta(days=self.review_intervals[0])

它的意思是指当前日期加上预设的复习间隔天数。

today
代表当前日期,通常通过datetime.date.today()获取。需要确保代码中已正确定义该变量。

datetime.timedelta
Python标准库中用于表示时间间隔的类。days参数指定需要增加的天数。

self.review_intervals[0]
从对象属性中获取的第一个复习间隔天数。review_intervals应为预定义的列表或数组,存储着不同阶段的复习间隔

 2. 记忆算法实现

def review_word(self, word, is_correct):"""记录单词复习结果并安排下次复习时间"""if word in self.word_data:info = self.word_data[word]info['last_reviewed'] = datetime.date.today()# 更新正确/错误计数if is_correct:info['correct_count'] += 1else:info['incorrect_count'] += 1# 根据记忆曲线安排下次复习时间review_count = min(info['review_count'], len(self.review_intervals) - 1)interval = self.review_intervals[review_count]# 如果不正确,缩短复习间隔if not is_correct:interval = max(1, interval // 2)info['next_review'] = datetime.date.today() + datetime.timedelta(days=interval)info['review_count'] += 1

这里我们需要做防越界处理:通过min()函数确保review_count不超过列表的最大索引。

3. 持久化存储

import json
import osdef load_data(self, data_file='word_memory_data.json'):"""加载已有的单词数据"""self.data_file = data_fileif os.path.exists(data_file):with open(data_file, 'r', encoding='utf-8') as f:data = json.load(f)# 将字符串日期转换为datetime.date对象for word, word_info in data.items():for key in ['added_date', 'last_reviewed', 'next_review']:if key in word_info and word_info[key]:word_info[key] = datetime.datetime.strptime(word_info[key], '%Y-%m-%d').date()self.word_data[word] = word_infodef save_data(self):"""保存单词数据到文件"""# 将datetime.date对象转换为字符串data_to_save = {}for word, word_info in self.word_data.items():word_info_copy = word_info.copy()for key in ['added_date', 'last_reviewed', 'next_review']:if key in word_info_copy and word_info_copy[key]:word_info_copy[key] = word_info_copy[key].strftime('%Y-%m-%d')data_to_save[word] = word_info_copywith open(self.data_file, 'w', encoding='utf-8') as f:json.dump(data_to_save, f, ensure_ascii=False, indent=2)

 4. 用户界面实现

在这里,我们来编写用户在命令行里交互时所能看到的用户界面:

def learn_mode(self):"""学习模式:逐个显示需要复习的单词"""words_to_review = self.get_words_to_review()if not words_to_review:print("恭喜!今天没有需要复习的单词。")returnprint(f"\n今天有 {len(words_to_review)} 个单词需要复习:")for word, info in words_to_review:print("\n" + "="*50)print(f"单词: {word}")input("按回车键查看意思...")print(f"意思: {info['meaning']}")if info['example']:print(f"例句: {info['example']}")while True:response = input("你记住了吗?(y/n): ").lower()if response in ['y', 'n']:self.review_word(word, response == 'y')breakprint("请输入 y 或 n")print("\n复习完成!")

5.整合与测试

接下来我们给程序添加main函数,就离大功告成不远了!

def main():system = WordMemorySystem()system.load_data()while True:print("\n" + "="*50)print("单词记忆系统")print("1. 添加新单词")print("2. 学习模式")print("3. 默写测试")print("4. 退出")choice = input("请选择操作: ")if choice == '1':word = input("输入单词: ").strip()meaning = input("输入意思: ").strip()example = input("输入例句 (可选): ").strip()system.add_word(word, meaning, example)system.save_data()elif choice == '2':system.learn_mode()system.save_data()elif choice == '3':system.test_mode()system.save_data()elif choice == '4':print("退出系统。")breakelse:print("无效选择,请重新输入。")

最后,我们来看看完整的代码:

import datetime
import json
import os
import random
from collections import defaultdictclass WordMemorySystem:def __init__(self, data_file='word_memory_data.json'):self.data_file = data_fileself.word_data = defaultdict(dict)self.load_data()# 记忆曲线间隔 (天)self.review_intervals = [1, 2, 4, 7, 15, 30, 60, 90]def load_data(self):"""加载已有的单词数据"""if os.path.exists(self.data_file):with open(self.data_file, 'r', encoding='utf-8') as f:data = json.load(f)# 将字符串日期转换为datetime.date对象for word, word_info in data.items():for key in ['added_date', 'last_reviewed', 'next_review']:if key in word_info and word_info[key]:word_info[key] = datetime.datetime.strptime(word_info[key], '%Y-%m-%d').date()self.word_data[word] = word_infodef save_data(self):"""保存单词数据到文件"""# 将datetime.date对象转换为字符串data_to_save = {}for word, word_info in self.word_data.items():word_info_copy = word_info.copy()for key in ['added_date', 'last_reviewed', 'next_review']:if key in word_info_copy and word_info_copy[key]:word_info_copy[key] = word_info_copy[key].strftime('%Y-%m-%d')data_to_save[word] = word_info_copywith open(self.data_file, 'w', encoding='utf-8') as f:json.dump(data_to_save, f, ensure_ascii=False, indent=2)def add_word(self, word, meaning, example=""):"""添加新单词"""today = datetime.date.today()if word not in self.word_data:self.word_data[word] = {'meaning': meaning,'example': example,'added_date': today,'last_reviewed': today,'next_review': today + datetime.timedelta(days=self.review_intervals[0]),'review_count': 0,'correct_count': 0,'incorrect_count': 0}print(f"已添加单词: {word} - {meaning}")else:print(f"单词 '{word}' 已存在")self.save_data()def get_words_to_review(self):"""获取今天需要复习的单词"""today = datetime.date.today()words_to_review = []for word, info in self.word_data.items():if 'next_review' in info and info['next_review'] <= today:words_to_review.append((word, info))# 按复习优先级排序 (先复习不熟悉的单词)words_to_review.sort(key=lambda x: (x[1]['incorrect_count'] / (x[1]['correct_count'] + x[1]['incorrect_count'] + 1),x[1]['next_review']), reverse=True)return words_to_reviewdef review_word(self, word, is_correct):"""记录单词复习结果并安排下次复习时间"""if word in self.word_data:info = self.word_data[word]info['last_reviewed'] = datetime.date.today()# 更新正确/错误计数if is_correct:info['correct_count'] += 1else:info['incorrect_count'] += 1# 根据记忆曲线安排下次复习时间review_count = min(info['review_count'], len(self.review_intervals) - 1)interval = self.review_intervals[review_count]# 如果不正确,缩短复习间隔if not is_correct:interval = max(1, interval // 2)info['next_review'] = datetime.date.today() + datetime.timedelta(days=interval)info['review_count'] += 1self.save_data()def learn_mode(self):"""学习模式:逐个显示需要复习的单词"""words_to_review = self.get_words_to_review()if not words_to_review:print("恭喜!今天没有需要复习的单词。")returnprint(f"\n今天有 {len(words_to_review)} 个单词需要复习:")for word, info in words_to_review:print("\n" + "=" * 50)print(f"单词: {word}")input("按回车键查看意思...")print(f"意思: {info['meaning']}")if info['example']:print(f"例句: {info['example']}")while True:response = input("你记住了吗?(y/n): ").lower()if response in ['y', 'n']:self.review_word(word, response == 'y')breakprint("请输入 y 或 n")print("\n复习完成!")def test_mode(self):"""测试模式:默写测试"""words_to_review = self.get_words_to_review()if not words_to_review:print("今天没有需要复习的单词。")returnprint("\n默写测试模式 (输入 q 退出)")random.shuffle(words_to_review)for word, info in words_to_review:print("\n" + "=" * 50)print(f"意思: {info['meaning']}")if info['example']:print(f"例句: {info['example']}")user_input = input("请输入对应的单词: ").strip()if user_input.lower() == 'q':breakif user_input.lower() == word.lower():print("正确!")self.review_word(word, True)else:print(f"错误!正确答案是: {word}")self.review_word(word, False)print("\n测试结束!")def main():system = WordMemorySystem()while True:print("\n" + "=" * 50)print("单词记忆系统")print("1. 添加新单词")print("2. 学习模式")print("3. 默写测试")print("4. 查看所有单词")print("5. 查看今天需要复习的单词")print("6. 退出")choice = input("请选择操作: ")if choice == '1':word = input("输入单词: ").strip()meaning = input("输入意思: ").strip()example = input("输入例句 (可选): ").strip()system.add_word(word, meaning, example)elif choice == '2':system.learn_mode()elif choice == '3':system.test_mode()elif choice == '4':if not system.word_data:print("还没有添加任何单词。")else:print("\n所有单词:")for i, (word, info) in enumerate(system.word_data.items(), 1):print(f"{i}. {word}: {info['meaning']}")if info['example']:print(f"   例句: {info['example']}")print(f"   添加日期: {info['added_date']}, 最后复习: {info['last_reviewed']}, 下次复习: {info['next_review']}")print(f"   正确: {info['correct_count']}, 错误: {info['incorrect_count']}")elif choice == '5':words_to_review = system.get_words_to_review()if not words_to_review:print("今天没有需要复习的单词。")else:print(f"\n今天需要复习 {len(words_to_review)} 个单词:")for i, (word, info) in enumerate(words_to_review, 1):print(f"{i}. {word}: {info['meaning']}")elif choice == '6':print("退出系统。")breakelse:print("无效选择,请重新输入。")if __name__ == "__main__":main()

好的!那么今天的内容就到这里了,现在我们只能在命令行中操作它,之后也可以给它添加图形化界面使它更加有趣。
 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/85559.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/85559.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【案例】性能优化在持续集成与持续交付中的应用

【案例】性能优化在持续集成与持续交付中的应用 为了更好地理解性能优化在CI/CD流程中的实际应用&#xff0c;本节将结合一个典型案例&#xff0c;从代码提交到部署上线的完整流程中&#xff0c;讲解如何嵌入性能检测与自动化优化机制&#xff0c;并使用结构化流程图直观展示关…

P7 QT项目----会学天气预报(完结)

7.8 QMap 在 Qt 中&#xff0c;如果你想要将 JSON 数据解析到一个 QMap 中&#xff0c;你可以遍历 JSON 对象的所有键值对&#xff0c;并将它们添加到 QMap 里。这个方法特别适合于当你的 JSON 对象是一个简单的键值对集合时。以下是一个如何实现这一点的示例。 示例&#…

操作系统笔记(关于进程引入和状态的切换)

1.前言 今天下午结束了英语的四六级考试&#xff0c;终于是结束了&#xff0c;最近的这个考试太密集&#xff0c;周四的专业基础课考试&#xff0c;周五的这个线性代数的考试和这个周六的英语四六级考试&#xff0c;吧我都要烤焦了&#xff0c;最近也是疲于应对这个考试&#…

M1芯片macOS安装Xinference部署大模型

如果你看的是官方手册&#xff1a;安装 — Xinference 千万不要直接运行&#xff1a; pip install "xinference[all]" 会遇到几个问题&#xff1a; 1&#xff09;Python版本如果太新可能安装失败 2&#xff09;全量安装会失败 3&#xff09;未科学上网可能会time…

【ONNX量化实战】使用ONNX Runtime进行静态量化

目录 什么是量化量化实现的原理实战准备数据执行量化 验证量化结语 什么是量化 量化是一种常见的深度学习技术&#xff0c;其目的在于将原始的深度神经网络权重从高位原始位数被动态缩放至低位目标尾数。例如从FP32&#xff08;32位浮点&#xff09;量化值INT8&#xff08;8位…

【量子计算】格罗弗算法

文章目录 &#x1f50d; 一、算法原理与工作机制⚡ 二、性能优势&#xff1a;二次加速的体现&#x1f310; 三、应用场景⚠️ 四、局限性与挑战&#x1f52e; 五、未来展望&#x1f48e; 总结 格罗弗算法&#xff08;Grover’s algorithm&#xff09;是量子计算领域的核心算法之…

C++ 互斥量

在 C 中&#xff0c;互斥量&#xff08;std::mutex&#xff09;是一种用于多线程编程中保护共享资源的机制&#xff0c;防止多个线程同时访问某个资源&#xff0c;从而避免数据竞争&#xff08;data race&#xff09;和不一致的问题。 &#x1f512; 一、基础用法&#xff1a;s…

CSS Content符号编码大全

资源宝整理分享&#xff1a;​https://www.httple.net​ 前端开发中常用的特殊符号查询工具&#xff0c;包含Unicode编码和HTML实体编码&#xff0c;方便开发者快速查找和使用各种符号。支持基本形状、箭头、数学符号、货币符号等多种分类。 前端最常用符号 图标形状十进制十…

RPC常见问题回答

项目流程和架构设计 1.服务端的功能&#xff1a; 1.提供rpc调用对应的函数 2.完成服务注册 服务发现 上线/下线通知 3.提供主题的操作 (创建/删除/订阅/取消订阅) 消息的发布 2.服务的模块划分 1.网络通信模块 net 底层套用的moude库 2.应用层通信协议模块 1.序列化 反序列化数…

【JavaEE】(3) 多线程2

一、常见的锁策略 1、乐观锁和悲观锁 悲观锁&#xff1a;预测锁冲突的概率较高。在锁中加阻塞操作。乐观锁&#xff1a;预测锁冲突的概率较低。使用忙等/版本号等&#xff0c;不产生阻塞。 2、轻量级锁和重量级锁 重量级锁&#xff1a;加锁的开销较大&#xff0c;线程等待锁…

创客匠人服务体系解析:知识 IP 变现的全链路赋能模型

在知识服务行业深度转型期&#xff0c;创客匠人通过 “工具 陪跑 圈层” 的三维服务体系&#xff0c;构建了从 IP 定位到商业变现的完整赋能链条。这套经过 5 万 知识博主验证的模型&#xff0c;不仅解决了 “内容生产 - 流量获取 - 用户转化” 的实操难题&#xff0c;更推动…

国产ARM/RISCV与OpenHarmony物联网项目(六)SF1节点开发

一、终端节点功能设计 1. 功能说明 终端节点设计的是基于鸿蒙操作系统的 TCP 服务器程序&#xff0c;用于监测空气质量并提供远程控制功能。与之前的光照监测程序相比&#xff0c;这个程序使用 E53_SF1 模块&#xff08;烟雾 / 气体传感器&#xff09;&#xff0c;主要功能包…

Plotly图表全面使用指南 -- Displaying Figures in Python

文中内容仅限技术学习与代码实践参考&#xff0c;市场存在不确定性&#xff0c;技术分析需谨慎验证&#xff0c;不构成任何投资建议。 在 Python 中显示图形 使用 Plotly 的 Python 图形库显示图形。 显示图形 Plotly的Python图形库plotly.py提供了多种显示图形的选项和方法…

getx用法详细解析以及注意事项

源码地址 在 Flutter 中&#xff0c;Get 是来自 get 包的一个轻量级、功能强大的状态管理与路由框架&#xff0c;常用于&#xff1a; 状态管理路由管理依赖注入&#xff08;DI&#xff09;Snackbar / Dialog / BottomSheet 管理本地化&#xff08;多语言&#xff09; 下面是 …

深度学习:人工神经网络基础概念

本文目录&#xff1a; 一、什么是神经网络二、如何构建神经网络三、神经网络内部状态值和激活值 一、什么是神经网络 人工神经网络&#xff08;Artificial Neural Network&#xff0c; 简写为ANN&#xff09;也简称为神经网络&#xff08;NN&#xff09;&#xff0c;是一种模仿…

Unity2D 街机风太空射击游戏 学习记录 #12环射道具的引入

概述 这是一款基于Unity引擎开发的2D街机风太空射击游戏&#xff0c;笔者并不是游戏开发人&#xff0c;作者是siki学院的凉鞋老师。 笔者只是学习项目&#xff0c;记录学习&#xff0c;同时也想帮助他人更好的学习这个项目 作者会记录学习这一期用到的知识&#xff0c;和一些…

网站如何启用HTTPS访问?本地内网部署的https网站怎么在外网打开?

在互联网的世界里&#xff0c;数据安全已经成为了每个网站和用户都不得不面对的问题。近期&#xff0c;网络信息泄露事件频发&#xff0c;让越来越多的网站开始重视起用户数据的安全性&#xff0c;因此启用HTTPS访问成为了一个热门话题。作为一名网络安全专家&#xff0c;我希望…

计算机网络-----详解网络原理TCP/IP(上)

文章目录 &#x1f4d5;1. UDP协议✏️1.1 UDP的特点✏️1.2 基于UDP的应用层协议 &#x1f4d5;2. TCP协议✏️2.1 TCP协议段格式✏️2.2 TCP协议特点之确认应答✏️2.3 TCP协议特点之超时重传✏️2.4 TCP协议特点之连接管理✏️2.5 TCP协议特点之滑动窗口✏️2.6 TCP协议特点…

Lora训练

一种大模型高效训练方式&#xff08;PEFT&#xff09; 目标&#xff1a; 训练有限的ΔW&#xff08;权重更新矩阵&#xff09; ΔW为低秩矩阵→ΔWAB&#xff08;其中A的大小为dr, B的大小为rk&#xff0c;且r<<min(d,k)&#xff09;→ 原本要更新的dk参数量大幅度缩减…

蓝牙 5.0 新特性全解析:传输距离与速度提升的底层逻辑(面试宝典版)

蓝牙技术自 1994 年诞生以来,已经经历了多次重大升级。作为当前主流的无线通信标准之一,蓝牙 5.0 在 2016 年发布后,凭借其显著的性能提升成为了物联网(IoT)、智能家居、可穿戴设备等领域的核心技术。本文将深入解析蓝牙 5.0 在传输距离和速度上的底层技术逻辑,并结合面试…