从一个文本fi中获取每个文本块的四行

2024-06-01 01:35:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做个小测验。在一个文本文件中,我有由subject、question、answer和一个空格(按顺序)组成的块。每行代表其中一项:

Histology What do megakaryocytes originate? Platelets.

Physiology Which physiological process does not occur in Glanzmann's thrombasthenia? Platelet aggregation.

Histology When in the erythropoietic process does the cell lose its nucleus? When in the ortochromatophilic stage.

Physiology Which phase of hemostasis features the action of coagulation factors? Secondary hemostasis.

Physiology What characterizes hemarthrosis? Blood in joint spaces.

Physiology Beyond being in circulation, a portion of platelets is also stored. Where? The spleen.

Physiology Which of the platelet zones includes the submembranous region? Peripheral zone.

我已经成功地编写了一个程序,它向用户显示问题,然后在用户说出来时显示答案。但是,我想随机显示这些问题。我用来顺序显示它们的灵感来自michaeldawson的《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行数据块分组,然后随机分组?如果我能按主题和问题来筛选,那就更好了。在


Tags: ofthetoanswerindeflinefunction
2条回答

为了组织起来,我会做一个简单的课堂或使用dicts。例如:

类实现

class Quiz():

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

您可以创建这些问题的实例,并为每个问题创建一个主题,根据它们的属性访问它们。因此:

^{pr2}$

您可以将新实例附加到一个列表中,然后将列表随机化

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'}}

但我觉得创建自己的类更容易组织起来。在

希望对你有点帮助。。。在

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!")

相关问题 更多 >