如何从列表中删除额外的“”字符

4
我尝试打开两个文本文件,读取它们的内容,并将其放入两个单独的临时文件中以便稍后调用。 我遇到了以下两个问题:
  1. 为什么test_questions列表中前两个字符串后面有这么多''?
  2. 为什么应该填充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

2
你是否熟悉return的概念?你正在打印list.append()file.write()return值,它们都是None。这对我来说似乎是不必要的。你可以直接调用函数而不会在控制台上输出None - Einliterflasche
2
你的函数 read_answers 中,将文件 read_answers.txt 的内容附加到列表 test_questions 中(如行 print(test_questions.append(i)) 所示)是有意为之吗?我原本以为你想将文件 read_answers.txt 的内容附加到此函数中的列表 test_answers 中。另外,打印 append 的结果没有任何意义,应该先附加再打印列表的新元素。 - Kapoios
4个回答

4

您的文件中有许多空白行(可能在末尾,您未注意到)。您可以通过运行以下命令来清理数据,以消除任何空白行:

# 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]

你好,感谢您的输入。但是,我不确定我理解您建议的代码。您能向我解释一下吗? - Japs6901

1
  1. 为什么会出现这么多''? 这是因为.readlines()将每一行读取为一个单独的元素。因此,您的列表看起来像['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']

现在,您正在执行以下操作:

file_read_q[0:5]
file_read_q[5:10]

理论上,每次获取5个元素,你只需要2个切片即可覆盖整个列表。但是for循环正在迭代列表的元素,并且你正在获取索引在列表中不存在的切片。因此,你得到的只是一个空列表[],连接后变成了''

但是如果索引超出了列表范围,为什么没有引发错误?

要了解原因,请参考此处
def read_quest():
    bank = open("test_question_bank", "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]).strip("\n")
        if temp_q:
            test_questions.append(temp_q)
        start += 5
        stop += 5
    bank.close()
您得到了一个空的test_answers,因为您从未实际将元素附加到test_answers中,而是执行了test_questions.append(...)。因此,请执行test_answers.append(...)
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")
        
        test_answers.append(i)
    ans.close()

干杯!这太棒了。 - Japs6901
1
@Japs6901 如果这个答案解决了问题,请考虑接受它:-) - user15801675

1
作为新手,有几个建议:
  1. 不要在方法外部声明变量(test_questionstest_answers),这很难调试和控制程序。
  2. 定义明确和易读的方法名称。 read_questionsread_ques 更好。
  3. 在打开文件时,使用 with open('..') 语法,而不是手动打开和关闭文件。
  4. 在你的方法 read_quest 中,尝试通过字符串模式提取问题,而不是跳过五行问题。
请查看下面的代码:
def read_questions():
    with open('test_question_bank.txt') as f:
        valid_lines = [x.strip() for x in f.readlines() if x.strip()]
        valid_questions = [x for x in valid_lines if not x.startswith('(')]

    return valid_questions

def read_answers():
    with open('test_correct_answers.txt') as f:
        valid_answers = [x.strip() for x in f.readlines() if x.strip()]

    return valid_answers


questions = read_questions()
valid_answers = read_answers()

print(questions)
print(valid_answers)

享受Python。


我不确定我理解你所做的,但我会使用这段代码来尝试理解发生了什么,谢谢。 - Japs6901

0

哇!感谢您的所有建议。我在这里确实学到了很多东西。对于我的第二个问题,我感到有点尴尬:我将内容添加到了错误的文件中!

至于第一个问题,有几个有用的解决方案 - 再次感谢 - 并且您教会了我问题出在如何迭代文件上。我想要做以下操作,这似乎也起作用了。我只是添加了一个if循环来测试开始索引是否超过了正在迭代的项目的索引。

if start < len(file_read_q):

如果这个解决方案存在潜在问题,也许你可以给我反馈。

再次感谢大家。

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:
        if start < len(file_read_q):
            temp_q = "".join(file_read_q[start:stop])
            test_questions.append(temp_q)
            start += 5
            stop += 5
        else:
            break    
    bank.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接