从文本文件中获取每行四行的文本块

时间:2013-10-14 15:45:10

标签: python list text random python-3.x

我正在尝试创建一个测验。在文本文件中,我有由主题,问题,答案和空白空间组成的块(在该顺序上)。每一行代表其中一项:

  

组织学巨核细胞起源于什么?血小板。

     

生理学Glanzmann's中没有发生哪种生理过程   症?血小板聚集。

     

组织学在红细胞生成过程中,细胞会失去它   核?在ortochromatophilic阶段。

     

生理学止血的哪个阶段具有的作用   凝血因子?继发性止血。

     

生理学什么是关节积血的特征?关节空间的血液。

     

生理学除了血液循环之外,还有一部分血小板   存储。哪里?脾脏。

     

生理学哪个血小板区域包括子膜   区域?周边区域。

我已经成功编写了一个程序,向用户显示问题,然后在用户这样说时显示答案。但是,我想随机显示问题。我曾经按顺序展示它们的灵感来自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行的块进行分组然后将它们随机化?如果我可以通过主题和问题过滤它们会更好。

2 个答案:

答案 0 :(得分: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 :(得分: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'}}

但我觉得通过创建自己的课程更容易组织。

希望有所帮助...