1. 程式人生 > 程式設計 >Python編寫打字訓練小程式

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,14))
e3 = Label(root,textvariable=v3,10),foreground='red')
e1.grid(row=0,column=1,padx=10,pady=20)
e2.grid(row=1,pady=20)
e3.grid(row=2,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,sticky=W,padx=30,pady=5)
user_only1 = Button(root,text="交卷",command=TypingTest.score,state='disable')
user_only1.grid(row=3,sticky=E,pady=5)
 
mainloop()

我們將最終的程式碼,打包成exe工具,即可脫離python環境,在單獨的電腦上執行exe檔案玩我們自己的打字練習題了:

總結

以上所述是小編給大家介紹的Python編寫打字訓練小程式,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!