gpt4 book ai didi

python - 如何从列表中删除额外的 ''

转载 作者:行者123 更新时间:2023-12-04 12:08:56 26 4
gpt4 key购买 nike

我试图打开两个文本文件,读取它们,并将内容放在两个单独的临时文件中,以便稍后调用它们。我有以下两个问题:

  • 为什么有这么多''在 test_questions 列表中的前两个字符串之后?
  • 为什么用于填充 test_answers 列表的字符串被附加到 test_questions 列表中?

  • 代码如下所示:
    from os import read

    # vars to hold questions and answers from question bank and answer bank in format ready for quiz iterations
    test_questions = []
    test_answers = []

    # placing questions in temp list called test_questions
    def read_quest():
    bank = open("test_question_bank.txt", "r+")
    bank.seek(0)
    file_read_q = bank.readlines()
    start = 0
    stop = 5
    for i in file_read_q:
    temp_q = "".join(file_read_q[start:stop])
    print(test_questions.append(temp_q))
    start += 5
    stop += 5
    bank.close()

    # placing answers in temp list called test_answers
    def read_answers():
    ans = open("test_correct_ans.txt", "r+")
    file_read_a = ans.readlines()
    ans.seek(0)
    for i in file_read_a:
    i = i.strip("\n")
    print(test_questions.append(i))
    ans.close()

    # adding questions
    def add_quest():
    bank = open("test_question_bank.txt", "a")
    correct_ans = open("test_correct_ans.txt", "a")
    prompt = input("Please write question: ")
    ansa = input("Write answer for choice a): ")
    ansb = input("Write answer for choice b): ")
    ansc = input("Write answer for choice c): ")
    correct_opt = input("Which option is the correct answer? ")
    temp_quest = prompt + "\n(a) " + ansa + "\n(b) " + ansb + "\n(c) " + ansc + "\n\n"
    temp_quest2 = "".join(temp_quest)
    print(bank.write(temp_quest2))
    print(correct_ans.write(correct_opt + "\n"))
    bank.close()
    correct_ans.close()

    read_quest()
    read_answers()
    print(test_questions)
    print(test_answers)
    #add_quest()
    输出如下所示:
    None
    None
    None
    None
    None
    None
    None
    None
    None
    None
    None
    None
    ['Where is North?\n(a) s\n(b) e\n(c) n\n\n', 'Where is South?\n(a) s\n(b) e\n(c) n\n\n', '', '', '', '', '', '', '', '', 'c', 'a']
    []
    test_question_bank.txt的内容看起来像这样:
    Where is North?
    (a) s
    (b) e
    (c) n

    Where is South?
    (a) s
    (b) e
    (c) n
    我的内容 test_correct_answers.txt看起来像这样:
    c
    a

    最佳答案

    您的文件中有很多空行(可能在最后,您没有注意到它们)。您可以通过运行以下命令来清除数据以去除任何空行:

    # For each question
    # If it is not a blank line
    # Add it to the new list
    test_questions = [question for question in test_questions if question]

    关于python - 如何从列表中删除额外的 '',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68609993/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com