Last active
August 29, 2015 14:22
-
-
Save richardjharris/9f6eac0465c4e27c1478 to your computer and use it in GitHub Desktop.
JLPT N1 Question (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse, collections, re | |
parser = argparse.ArgumentParser(description='Test yourself on the JLPT N1 question set') | |
parser.add_argument( | |
'--start', type=int, help='Question number to start from', default=1) | |
parser.add_argument( | |
'--question-file', type=str, help='Path to question file', default='JLPT1 Questions.txt') | |
args = parser.parse_args() | |
def run_quiz(start, question_file): | |
for number, question in enumerate(load_questions(question_file), 1): | |
if number < start: | |
continue | |
while True: | |
print("Question: #{}\n{}".format(number, question.question)) | |
guess = prompt(question.answers) | |
if guess == question.correct: | |
correct = question.answers[question.correct - 1] | |
print("CORRECT! The answer is {}".format(correct)) | |
print(re.sub("( +)", "(" + correct + ")", question.question)) | |
break | |
else: | |
print("Sorry, that's wrong, try again!") | |
def prompt(answers): | |
for num, answer in enumerate(answers, 1): | |
print("{}) {}".format(num, answer)) | |
while True: | |
guess = input("Answer: ") | |
try: | |
if guess.lower().startswith('q'): | |
exit() | |
elif 0 < int(guess) <= num: | |
return int(guess) | |
except ValueError: | |
pass | |
print("Invalid answer, try again!") | |
def load_questions(question_file): | |
ANSWER_PATTERN = r'\s*1\)(.*?) 2\)(.*?) 3\)(.*?) 4\)(.*?)\s*$' | |
Question = collections.namedtuple('Question', 'question answers correct') | |
with open(question_file) as file: | |
while True: | |
line = next(file) | |
if not line: | |
break # end of file | |
number, question = re.match(r"(\d+\s*)?(.*)$", line, re.M).groups() | |
answer_same_line = re.search(ANSWER_PATTERN, question, re.M) | |
if answer_same_line: | |
question = question.replace(answer_same_line.group(0), '') | |
answers = answer_same_line.group(1,2,3,4) | |
else: | |
answers = re.match(ANSWER_PATTERN, next(file), re.M).group(1,2,3,4) | |
# Don't return questions 1..100 as no answer is provided | |
if number and int(number) > 100: | |
correct = re.search(r'答案:(\d+)', next(file), re.M).group(1) | |
yield Question(question.strip(), list(map(str.strip, answers)), int(correct)) | |
run_quiz(start=args.start, question_file=args.question_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment