「青少年编程竞赛交流群」已成立(适合6至18周岁的青少年),公众号后台回复【Scratch】或【Python】,即可进入。如果加入了之前的社群不需要重复加入。
微信后台回复“资料下载”可获取以往学习的材料(视频、代码、文档)。
编程题 “我要背单词”是来自「青少年编程竞赛交流群」中 「黄羽恒」 小朋友的作品。
背单词是一件让小朋友们非常头痛的事情,现在我们需要用Python来辅助小朋友们记忆单词。
首先,利用字典的方式创建单词本,key为单词,value为单词的中文含义。
其次,背单词有两种模式,第一种模式为根据英文记忆中文,另一种模式为根据中文记忆英文。
再次,程序可以读出英文以及中文,并显示阅读单词的进度,利用听觉辅助记忆。
最后,单词本中所有单词背诵完毕后,程序自动关闭。
1. 思路分析 显示单词本中的单词,以及单词的阅读进度可以利用Pygame实现,阅读单词可以利用pyttsx3实现。
Pygame是一套用来写游戏的Python模块。它是基于SDL(Simple DirectMedia Layer)库的,它使你可以用Python语言创建完全界面化的游戏和多媒体程序。
安装Pygame:
pip install pygame
pyttsx3 是Python中的文本到语音转换库。与其它库不同,它可以脱机工作。
安装pyttsx3:
pip install pyttsx3
由于篇幅原因,这两个库的用法,我们在后面会单独写图文来介绍。
2. 程序代码 import pygameimport pyttsx3import sys pygame.init() screen = pygame.display.set_mode((600 , 340 )) pygame.display.set_caption('我要背单词' ) clock = pygame.time.Clock() engine = pyttsx3.init()# 定义单词本 words = { 'travel' : '旅行' , 'break' : '摔伤' , 'medicine' : '药' , 'restaurant' : '餐馆' , 'policeman' : '警察' , 'scientist' : '科学家' , 'inventor' : '发明家' , 'information' : '信息' , '' : '复习完毕' }# 模式 # mode = int(input('(根据单词背解释(写1)、根据解释背单词(写2))')) - 1 mode = 0 WHITE = (255 , 255 , 255 ) BLACK = (0 , 0 , 0 ) LIG_TH_YELLOW = (255 , 251 , 224 ) index = 0 while True : count = 0 word = '' # 当前正在读的单词 trans = '' # 单词正在读的翻译 for key in words: if count == index: if mode == 0 : word = key trans = words[key] else : word = words[key] trans = key break count += 1 index += 1 screen.fill(LIG_TH_YELLOW) # 进度条 percent_num = round(index / len(words) * 100 ) pygame.draw.lines(screen, BLACK, False , ((0 , 300 ), (600 , 300 )), 1 ) pygame.draw.rect(screen, BLACK, (0 , 300 , 600 * (percent_num / 100 ), 300 )) # 进度文字 font = pygame.font.SysFont('SimHei' , 20 ) percent_str = font.render('进度' + str(percent_num) + '%' , False , WHITE) screen.blit(percent_str, (20 , 310 )) # 读写生词 if word != '' : font = pygame.font.SysFont('SimHei' , 80 ) rect = font.render(word, False , BLACK) length = len(word) left = (540 - length * 41 ) / 2 screen.blit(rect, (left, 30 )) pygame.draw.rect(screen, BLACK, (20 , 20 , 560 , 140 ), 1 ) pygame.display.update() engine.say(word) engine.runAndWait() # 读写翻译 if trans != '' : trans_font = pygame.font.SysFont('SimHei' , 40 ) rect = trans_font.render(trans, False , BLACK) length = len(trans) left = (600 - length * 59 ) / 2 screen.blit(rect, (left, 200 )) pygame.display.update() engine.say(trans) engine.runAndWait() # 完成后停止 if index == len(words): pygame.quit() engine.stop() sys.exit() clock.tick(30 )
3. 结果展示