移至主內容
首頁
SLAT Blogs

主導覽

  • 首頁
使用者帳號選單
  • 登入

導航連結

  1. 首頁
  2. 部落格
  3. 肥貓的異想世界

試用Python製作一支簡單的考試程式

By 肥貓, 18 九月, 2025
考試程式 Live Demo

網路上常見如阿摩、MOSME等線上題庫,讓使用者在上面做考古題、做完對答案...諸如此類。但是這種網站畢竟是套裝軟體,若想自己修改參數,例如題目考啥、考幾題、答對得幾分、答錯倒扣幾分、甚至答題紀錄等不甚方便。有時還需要付錢+登入才能使用。最近肥貓在準備轉職的考試,想說這些功能如果網站沒有,自己弄一個不就得了嗎?於是用Python做出一支簡單的考試程式來用。

  1. 題庫建立

    為避免版權爭議,我就不提供原始的題庫,就隨便出幾題來demo。題庫(csv)格式

    但是看我的題庫檔案(以csv格式存起來,編碼請用UTF-8),可清楚看到使用的欄位不外乎唯獨識別碼(pid)(這是用在給系統隨機變數出題用)、每屆題目的索引值(index)、題目主文(要不要前面有編號就自己決定)、答案、來源(這裡更像第幾年第幾次考試的題庫)、url(如果你是從某個網站貼過來的,這樣對照比較方便)、解析等。這些即使不是技術人,應該都很容易了解。

    2. 在Spyder建立的程式碼

    因為這部落格的系統限制,我只能用很粗糙的方式貼上程式碼,建議您貼到Notepad++之類的編輯器看code比較不會傷眼:

    當然,檔案路徑和參數要取決於系統配置和需求自己改,這點就不再贅述了。

#這是分隔線

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 13 16:13:25 2024

@author: fattabby
"""
import time
import pandas as pd
import numpy as np
import os

#讀取題庫位置
if os.name=="posix":
   print("you are using Linux or Mac")
   pathname = '/home/{}/Nextcloud/tougu_test'.format(os.getlogin())
else:
   print("you are using Windows")
   pathname = 'C:/Users/{}/Nextcloud/tougu_test'.format(os.getlogin())
try:
   os.chdir(pathname)
except Exception:
   os.makedirs(pathname, exist_ok=True)
   os.chdir(pathname)

database=pd.read_csv("投顧考古題.csv",index_col=0)
#若限定要哪一年內或哪幾科試題,可以用這個去抓
#database=database[(database["source"].str.contains("2024年") | database["source"].str.contains("2025年")| database["source"].str.contains("2023年"))]
#database=database[(database["source"].str.contains("2025年"))]
#database=database[(database["source"].str.contains("法規"))]
#database=database[(database["source"].str.contains(subject))]
subject="投顧"
n_questions=4
x1 = np.random.choice(int(database.index[-1]),n_questions,replace=False)
#從6549題中隨機出50題 #幾題是由size去控制
#x1 = np.random.randint(low=0, high=int(database.count()[0]), size=(5,))
print("考試開始")
start_time=time.time()
testinput=pd.DataFrame([],columns=["pid","questions","actual_answer","input_answer"])
#testinput=pd.DataFrame([],columns=["pid","questions","actual_answer","input_answer"])

for i in x1:
   ongoing_test=pd.DataFrame([],index=["pid","questions","source","actual_answer","input_answer","help"]).transpose()
   ongoing_test_pid=database["index"][i]
   ongoing_test_questions=database["questions"][i]
   ongoing_test_actual_answer=database["answers"][i]
   ongoing_test_input_answer=str.upper(input(database["questions"].iloc[i]))
   ongoing_test_input_source=database["source"][i]
   ongoing_test_help=database["help"][i]
   ongoing_test=pd.DataFrame([ongoing_test_pid,
                           ongoing_test_questions,
                           ongoing_test_input_source,
                           ongoing_test_actual_answer,
                           ongoing_test_input_answer,
                           ongoing_test_help],
                          index=["pid","questions","source","actual_answer","input_answer","help"]).transpose()
   testinput=pd.concat([testinput,ongoing_test])

start_time2=time.time()    
print("考試結束")    
print("本次考試費時:", int(start_time2-start_time), "秒")
testinput["correctcheck"]=(testinput["input_answer"]==testinput["actual_answer"])
#計分機制與倒扣(如果有;最後兩個參數分別為答對得幾分,答錯倒扣幾分)
testinput['score'] = np.where(testinput['input_answer']==testinput["actual_answer"], (100/n_questions), -1)
#if testinput["correctcheck"] is True:
#    testinput["score"]=2.5
#else:
#    testinput["score"]=-1

total_score=testinput["score"].sum()

print("本次考試總得分為:", total_score)
t = time.time()
t1 = time.localtime(t)
testinput=testinput.sort_values("pid")
testinput.to_csv("考試結果_{}_{}.csv".format(subject,str(t1.tm_year)+str(t1.tm_mon)+str(t1.tm_mday)+"_"+str(t1.tm_hour)+str(t1.tm_min)),encoding="utf-8")
testinput_incorrect=testinput[(testinput["correctcheck"]==False)]
testinput_incorrect.to_csv("答錯題目_{}_{}.csv".format(subject,str(t1.tm_year)+str(t1.tm_mon)+str(t1.tm_mday)+"_"+str(t1.tm_hour)+str(t1.tm_min)),encoding="utf-8")

#這是分隔線

若程式在您的環境跑得起來,理論上會看到類似這樣的畫面:

(這裡答題請輸入a、b、c、d,大小寫沒差,我設定成一律轉成大寫)

除了告訴您得幾分,我還附加了計時器功能,方便練答題速度用。

然後應該會看到這圖中我選起來的檔案,這就是您的答題紀錄,還有您答錯了哪些題目,被扣了幾分等:

live demo 2答題紀錄節錄

這就是簡單的作答與對答案程式。

雖然為了更貼近考場情境,我把考古題出題順序調整成可隨機出,但是選項的部份就暫時沒辦法了,想說這不是那麼重要。若只是自己想離線考一考,應該還算夠用。

Blog tags
Python
  • 肥貓的異想世界

部落格列表

管理日誌
LibreOffice 正體中文文件
肥貓的異想世界
軟體自由運動部落格
馬哥的大小事
My Libre World
社會派宅爸

最新文章

LO Conf 2025 精彩回顧:奧地利軍隊的開源轉型之路
試用Python製作一支簡單的爬蟲程式
試用Python製作一支簡單的考試程式
Interview with Sandy Corzeta, Admin of Indonesia's Fediverse Instance 'misskey.id'
簡單處理在Ubuntu終端機啟動Miniconda的問題
在LibreOffice Calc利用Vlookup做精準搜尋
現在就加入 LibreOffice 團隊當全職開發者,處理 RTL/CTL/CJK 等事宜!
[JS 筆記] 可選串連、條件三元、falsy、some與includes
用QGIS + OpenStreetMap + Python 處理線形地理資料
申請墨西哥簽證的經驗談
0805 ITTS 田野筆記:與印尼開源社群的初次接觸
Setting up Mailman3 on Debian 11 (Bullseye)
Powered by Drupal