2013-10-14 4 views
0

퀴즈를 만들려고합니다. 텍스트 파일에서 주제, 질문, 대답 및 빈 공간 (순서대로)으로 구성된 블록이 있습니다. 각 라인은 다음 항목 중 하나를 나타냅니다.텍스트 파일에서 각각 네 줄의 텍스트 블록 가져 오기

조직학 거핵 세포는 어떻게 생겼습니까? 혈소판.

생리학 Glanzmann의 혈전증에서 어떤 생리 학적 과정이 일어나지 않습니까? 혈소판 응집.

조직학 적혈구 생성 과정에서 세포가 핵을 잃어 버렸습니까? ortochromatophilic 단계에있을 때.

생리학 응고 인자의 작용을 특징으로하는 지혈 단계는 무엇입니까? 2 차 지혈.

생리학 관절염의 특징은 무엇입니까? 관절 공간의 피.

생리학 혈액 순환을 넘어서서 일부 혈소판은 또한 으로 저장됩니다. 어디에? 비장.

생리학 영역을 포함하는 혈소판 구역은 어느 것입니까? 주변 구역.

사용자가 질문을하고 사용자가 대답 할 때 대답을 나타내는 프로그램을 성공적으로 코딩했습니다. 그러나 무작위로 질문을 표시하고 싶었습니다. 필자가 순차적으로 표시 한 것은 Michael Dawson의 저서 "절대 초보자 용 Python 프로그래밍"에서 영감을 얻은 것입니다. 나는 저자가 밀접하게 보여준 구조를 따랐다. 코드는 다음과 같습니다.

#File opening function. Receives a file name, a mode and returns the opened file. 
def open_file(file_name, mode): 
    try: 
     file = open(file_name, mode) 
    except: 
     print("An error has ocurred. Please make sure that the file is in the correct location.") 
     input("Press enter to exit.") 
     sys.exit() 
    else: 
     return file 

#Next line function. Receives a file and returns the read line. 
def next_line(file): 
    line = file.readline() 
    line = line.replace("/", "\n") 
    return line 

#Next block function. Receives a file and returns the next block (set of three lines comprising subject, question and answer. 
def next_block(file): 
    subject = next_line(file) 
    question = next_line(file) 
    answer = next_line(file) 
    empty = next_line(file) 
    return subject, question, answer, empty 

#Welcome function. Introduces the user into the quizz, explaining its mechanics. 
def welcome(): 
    print(""" 
     Welcome to PITAA (Pain In The Ass Asker)! 
    PITAA will ask you random questions. You can then tell it to 
    reveal the correct answer. It does not evaluate your choice, 
    so you must see how many you got right by yourself. 
    """) 

def main(): 
    welcome() 
    file = open_file("quizz.txt", "r") 
    store = open_file("store.bat", "w") 
    subject, question, answer, empty = next_block(file) 
    while subject: 
     print("\n") 
     print("Subject: ", subject) 
     print("Question: ", question) 
     input("Press enter to reveal answer") 
     print("Answer: ", answer) 
     print("\n") 
     subject, question, answer, empty = next_block(file) 
    file.close() 
    print("\nQuizz over! Have a nice day!") 

#Running the program 
main() 
input("Press the enter key to exit.") 

4 줄 블록을 그룹화하고 임의화할 수 있습니까? 주제와 질문으로 필터링 할 수 있다면 더 좋을 것입니다.

답변

1
import random 

def open_file(file_name, mode): 
    try: 
     file = open(file_name, mode) 
    except: 
     print("An error has ocurred. Please make sure that the file is in the correct location.") 
     input("Press enter to exit.") 
     sys.exit() 
    else: 
     return file 

def replace_linebreaks(value): 
    value.replace("/", "\n") 

def main(): 
    welcome() 
# store = open_file("store.bat", "w") 
    file = open_file("quizz.txt", "r") 
    questions = file.read().split('\n\n') # if UNIX line endings 
    file.close() 
    random.shuffle(questions) 

    for question in questions.splitlines(): 
     subject, question, answer, empty = map(replace_linebreaks, question) 

     print("\n") 
     print("Subject: ", subject) 
     print("Question: ", question) 
     input("Press enter to reveal answer") 
     print("Answer: ", answer) 
     print("\n") 
     subject, question, answer, empty = next_block(file) 
    print("\nQuizz over! Have a nice day!") 
1

정리하려면 간단한 클래스를 만들거나 dicts를 사용합니다. 예를 들어 :

클래스 구현

class Quiz(): 

    def __init__(self, question, answer, subject): 
     self.question = question 
     self.answer = answer 
     self.subject = subject 

당신은 그 질문의 인스턴스를 만들고 그 속성에 따라 그들에게 접근, 그들 각각의 제목을 만들 수 있습니다. 예를 들면 :

q = Quiz("Question 1", "Answer 1", "Chemistry") 
print(q.subject) 
>>> Chemistry 

당신은 목록에 새 인스턴스를 추가하고 당신이 중첩 된 사전이 할 수있는 등

import random #Look up the python docs for this as there are several methods to use 

new_list = [] 
new_list.append(q) 
random.choice(new_list) #returns a random object in the list 

등의 목록을 무작위하고 '주제'를 기반으로 드릴 다운 할 수 있습니다

new_dict = {'subject': {'question': 'this is the question', 
         'answer': 'This is the answer'}} 

그러나 나는 자신의 수업을 만들어서 편성하는 것이 더 쉽다고 느낍니다.

작은 도움이 되길 희망합니다.