Program file
問題會儲存在Exercise/Exercise.xlsx file
Source code
import openpyxl
import os
import random
import glob
from os.path import basename
import datetime
import ntpath
script_dir = os.path.dirname(__file__)
result_directory = os.path.join(script_dir, 'results')
archive_directory = os.path.join(script_dir, 'archive')
def archiveResult():
if not os.path.exists(archive_directory):
os.makedirs(archive_directory)
archivedir = archive_directory + '\\' + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if not os.path.exists(archivedir):
os.makedirs(archivedir)
list_of_files = glob.glob(result_directory + '/*')
for file in list_of_files:
os.rename(file, archivedir + '\\' + ntpath.basename(file))
def checkHasAnswerQuestion(Question):
hasAnswer = False
list_of_files = sorted(glob.glob(result_directory + '/*'), key=os.path.getmtime)
if list_of_files:
latestFile = max(list_of_files, key=os.path.getctime)
file = open(latestFile, "r")
for line in file:
RecordQuestionNO = line.split(".", 1)[0]
if RecordQuestionNO == Question.QuestionNO:
hasAnswer = True
return hasAnswer
def checkQuestionAvailable(Question):
available = True
list_of_files = sorted(glob.glob(result_directory + '/*'), key=os.path.getmtime)
accumulateCorrentCount = 0
for fileitem in list_of_files:
file = open(fileitem, "r")
for line in file:
RecordQuestionNO = line.split(".", 1)[0]
RecordAnswer = line.split(".", 1)[1].replace('\n', '')
if (RecordQuestionNO == Question.QuestionNO and RecordAnswer == "O" ):
accumulateCorrentCount += 1
elif (RecordQuestionNO == Question.QuestionNO and RecordAnswer == "X" ):
accumulateCorrentCount = 0
if (Question.QuestionType == "MC" and accumulateCorrentCount == 3):
available = False
elif(Question.QuestionType == "FITB" and accumulateCorrentCount == 1):
available = False
return available
def getAnsweredQuestions(path):
AnsweredQuestions = []
file = open(path, "r")
for line in file:
AnsweredQuestions.append(line.split(".", 1)[0])
return AnsweredQuestions
def record(QuestionNo, IsCorrect):
latestFile = result_directory + "\\1.txt";
if not os.path.exists(result_directory):
os.makedirs(result_directory)
else:
list_of_files = glob.glob(result_directory + '/*') # * means all if need specific format then *.csv
if list_of_files:
latestFile = max(list_of_files, key=os.path.getctime)
AnsweredQuestions = getAnsweredQuestions(latestFile)
if QuestionNo in AnsweredQuestions:
latestFile = result_directory + "\\" + str(int(basename(latestFile).split(".")[0]) + 1) +".txt"
with open(latestFile, 'a') as the_file:
the_file.write(str(QuestionNo) + '.' + ("O" if IsCorrect else "X"))
the_file.write("\n")
def getAllQuestionsFromExcel():
rel_path = "Exercise\Exercise.xlsx"
abs_file_path = os.path.join(script_dir, rel_path)
wb_obj = openpyxl.load_workbook(abs_file_path)
sheet = wb_obj.active
max_col = sheet.max_column
m_row = sheet.max_row
Questions = []
for i in range(2, m_row + 1):
col_value = []
Answer = []
Option = []
QuestionNo = ""
QuestionType = ""
QuestionText = ""
for col in range(1, max_col + 1):
cell_obj = sheet.cell(row=i, column=col)
value = cell_obj.value
if col in [1]:
QuestionNo = value
elif col in [2]:
QuestionText = value
elif col in [3,4,5,6,7]:
if value:
Answer.append(str(value))
elif col in [8,9,10,11,12,13,14,15,16,17]:
if value:
Option.append(str(value))
elif col in [18]:
QuestionType = value
item = Question(QuestionNo, QuestionText, Answer, Option, QuestionType)
Questions.append(item)
return Questions
def getQuestions():
AvailableQuestions = []
Questions = getAllQuestionsFromExcel()
for Question in Questions:
if (checkQuestionAvailable(Question) and not checkHasAnswerQuestion(Question)):
AvailableQuestions.append(Question)
if not AvailableQuestions:
for Question in Questions:
if (checkQuestionAvailable(Question)):
AvailableQuestions.append(Question)
random.shuffle(AvailableQuestions)
return AvailableQuestions
class Question(object):
def __init__(self, QuestionNo, Question, Answer = [], Option = [], QuestionType =""):
self.QuestionNO = QuestionNo
self.Question = Question
self.Answer = Answer
self.Option = Option
self.QuestionType = QuestionType
NumberToWord = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', \
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'}
Questions = getQuestions()
if not Questions:
print("All questions is completed, do you want to restart? Y / N")
UserInput = input()
if (UserInput.upper() == "Y"):
archiveResult()
Questions = getQuestions()
elif(UserInput.upper() == "N"):
exit()
for i, Question in enumerate(Questions):
print(Question.Question)
Options = []
Options.extend(Question.Option)
AnswersNo = []
AnswerText = []
if Question.QuestionType == 'MC':
AnswerText = Question.Answer
for j, Option in enumerate(Options):
print(str(j + 1) + ". " + str(Option).strip())
if (Option in Question.Answer):
AnswersNo.append(str(j + 1))
if Question.QuestionType == 'FITB':
AnswerText = Question.Answer
print()
if Question.QuestionType == 'MC':
print("Please choose " + NumberToWord[len( Question.Answer)] +" answer")
elif Question.QuestionType == 'FITB':
print("Please fill in the blanks")
UserInputs = []
NoOfAnswer = len(Question.Answer)
for number in range(NoOfAnswer):
UserInputs.append(input().strip())
Correct = True
if Question.QuestionType == 'MC':
for Text in UserInputs:
if Text not in AnswersNo:
Correct = False
if Question.QuestionType == 'FITB':
for n, Text in enumerate(AnswerText):
if UserInputs[n].upper() != Text.upper():
Correct = False
if Correct:
print('Corrent. Your answer is ' + " , ".join(Question.Answer))
record(Question.QuestionNO, True)
else:
print('Incorrect, Correct answer is ' + " , ".join(Question.Answer))
record(Question.QuestionNO, False)
print()
input("Press enter to exit")