【问题标题】:Get blocks of text with four lines each from a text file从文本文件中获取每行四行的文本块
【发布时间】:2013-10-14 15:45:10
【问题描述】:

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

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

生理学 格兰兹曼不发生哪个生理过程 血小板无力症?血小板聚集。

组织学 在红细胞生成过程中,细胞是否会失去它的 核?处于嗜正染色阶段。

生理学止血的哪个阶段具有以下作用 凝血因子?二次止血。

生理学 关节积血有什么特点?关节间隙有血。

生理学 除了在循环中,一部分血小板也在 存储。在哪里?脾脏。

生理学 地区?周边地带。

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

【问题讨论】:

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


    【解决方案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!")
    

    【讨论】:

      【解决方案2】:

      为了组织我会做一个简单的类或使用字典。例如:

      类实现

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

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

      希望对你有所帮助……

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-03
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-15
        相关资源
        最近更新 更多