Python编写打字训练小程序

yipeiwu_com6年前Python基础

你眼中的程序猿

别人眼中的程序猿,是什么样子?打字如飞,各种炫酷的页面切换,一个个好似黑客般的网站破解。可现实呢? 二指禅的敲键盘,写一行代码,查半天百度…那么如何能让我们从外表上变得更像一个程序猿呢?当然是训练我们的打字速度了啊!

训练打字

很羡慕那些盲打速度炒鸡快的人,看起来就比较炫酷。但很多IT男打字速度并不快,甚至还有些二指禅的朋友们,太影响装13效果了。那么今天我们就来使用Python写一个打字训练的小工具吧。先来看看使用效果…

我们使用Python内置的GUI模块Tkinter来编写一个打字测试的小工具。点击开始测试,系统随机生成20个字符串,然后用户按照题目进行作答后,点击交卷,系统将对比我们的输入结果,来计算正确率,并使用涂色将系统与用户的答案进行对比。

生成随机数

首先我们需要生成键盘上的字符。当然我们可以0-9,A-Z,a-z,!-)等等的一个个枚举出键盘上的按键。但有没有更快捷的操作呢?你需要了解下string模块。这里介绍下几个string默认提供的内容:

import string
# 列举数字
string.digits
>>> '0123456789'
# 列举小写字母
string.ascii_lowercase
>>> 'abcdefghijklmnopqrstuvwxyz'
# 列举大写字母
string.ascii_uppercase
>>> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# 列举所有标点符号
string.punctuation
>>> '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
# 列举所有空白符
string.whitespace
>>> ' \t\n\r\x0b\x0c'
 
string.ascii_letters =
  string.ascii_lowercase + string.ascii_uppercase
string.printable =
  string.ascii_letters + string.digits
  + string.whitespace + string.punctuation

剩余的内容,我们只需要进行相关读写判断即可,整体代码如下:

# -*- coding: utf-8 -*-
# @Author  : 王翔
# @JianShu : 清风Python
# @Date   : 2019/8/25 20:59
# @Software : PyCharm
# @version :Python 3.7.3
# @File   : TypingTest.py
 
from tkinter import *
import random
import string
from datetime import datetime
 
root = Tk()
root.title("Python打字练习题 By:清风Python")
Label(root, text='系统题目:').grid(row=0)
Label(root, text='用户作答:').grid(row=1)
Label(root, text='考试结果:').grid(row=2)
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
v1.set("点击'开始测试'按钮开始出题")
e1 = Entry(root, text=v1, state='disabled', width=40, font=('宋体', 14))
e2 = Entry(root, textvariable=v2, width=40, font=('宋体', 14))
e3 = Label(root, textvariable=v3, width=40, font=('宋体', 10), foreground='red')
e1.grid(row=0, column=1, padx=10, pady=20)
e2.grid(row=1, column=1, padx=10, pady=20)
e3.grid(row=2, column=1, padx=10, pady=20)
text = Text(root, width=80, height=7)
text.grid(row=4, column=0, columnspan=2, pady=5)
 
 
class TypingTest:
  def __init__(self):
    self.time_list = []
    self.letterNum = 20
    self.letterStr = ''.join(random.sample(string.printable.split(' ')[0], self.letterNum))
    self.examination_paper = ''
 
  def time_calc(self):
    self.time_list.append(datetime.now())
    yield
 
  def create_exam(self):
    text.delete(0.0, END)
    # e3.delete(0, END)
    v1.set(self.letterStr)
    self.time_calc().__next__()
    text.insert(END, "开始:%s \n" % str(self.time_list[-1]))
    user_only1.config(state='active')
 
  def score(self):
    wrong_index = []
    self.time_calc().__next__()
    text.insert(END, "结束:%s\n" % str(self.time_list[-1]))
    use_time = (self.time_list[-1] - self.time_list[-2]).seconds
    self.examination_paper = v2.get()
    if len(self.examination_paper) > self.letterNum:
      v3.set("输入数据有误,作答数大于考题数")
    else:
      right_num = 0
      for z in range(len(self.examination_paper)):
        if self.examination_paper[z] == self.letterStr[z]:
          right_num += 1
        else:
          wrong_index.append(z)
      if right_num == self.letterNum:
        v3.set("完全正确,正确率%.2f%%用时:%s秒" % ((right_num * 1.0) / self.letterNum * 100, use_time))
      else:
        v3.set("正确率%.2f%%用时:%s 秒" % ((right_num * 1.0) / self.letterNum * 100, use_time))
        # e2.delete(0, END)
        text.insert(END, "题目:%s\n" % self.letterStr)
        tag_info = list(map(lambda x: '4.' + str(x + 3), wrong_index))
        text.insert(END, "作答:%s\n" % self.examination_paper)
        for i in range(len(tag_info)):
          text.tag_add("tag1", tag_info[i])
          text.tag_config("tag1", background='red')
          user_only1.config(state='disabled')
 
 
TypingTest = TypingTest()
Button(root, text="开始测试", width=10, command=TypingTest.create_exam).grid(row=3, column=0, sticky=W, padx=30, pady=5)
user_only1 = Button(root, text="交卷", width=10, command=TypingTest.score, state='disable')
user_only1.grid(row=3, column=1, sticky=E, padx=30, pady=5)
 
mainloop()

我们将最终的代码,打包成exe工具,即可脱离python环境,在单独的电脑上执行exe文件玩我们自己的打字练习题了:

总结

以上所述是小编给大家介绍的Python编写打字训练小程序,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

使用Python画出小人发射爱心的代码

使用Python画出小人发射爱心的代码

我就废话不多说了,直接上代码吧! #2.14 from turtle import * from time import sleep def go_to(x, y): up(...

Python中线程的MQ消息队列实现以及消息队列的优点解析

“消息队列”是在消息的传输过程中保存消息的容器。消息队列管理器在将消息从它的源中继到它的目标时充当中间人。队列的主要目的是提供路由并保证消息的传递;如果发送消息时接收者不可用,消息队列会...

python 实现将list转成字符串,中间用空格隔开

今天想输出一个list,中间用空格隔开。当然用循环可以搞定,但是这个也太不象python的风格了。 找了半天,网上都说使用" ".join(a)的办法,但是python3不支持,在sta...

python3实现SMTP发送邮件详细教程

python3实现SMTP发送邮件详细教程

简介   Python发送邮件的教程本人在网站搜索的时候搜索出来了一大堆,但是都是说了一大堆原理然后就推出了实现代码,我测试用给出的代码进行发送邮件时都不成功,后...

python实现函数极小值

python实现函数极小值

这里用到的是scipy.optimize的fmin和fminbound import numpy as np from matplotlib import pyplot as plt...