我正在用 Python 创建一个您可以编辑的测验,但其中一个部分需要将问题保存在文件中。在这部分代码中,我试图读取文件,然后将读取的内容放入列表中,这样我就可以拉出某些问题以显示在某些按钮上。但我不断收到错误消息,提示该列表不可调用。
我尝试使用 strip 去除出现的引号字符串,但出现错误提示
"list" object has no attribute "strip"
我是 Python 的新手,所以我正在努力寻找其他修复方法,我尝试将打印隔离在不同的行中,然后将其放入列表中,但最终却说该列表不可再次调用.
textquestions=open('listofquestions','r')
allthequestions = textquestions.readlines()
forbuttons=[print(allthequestions)]
textquestions.close
q1 = forbuttons(0)
buttonq1 = tk.Button(self, text=forbuttons[q1][0])
buttonq1.pack()
文件只写了这个,没有别的(填充问题让它首先工作):
["What would you wear to work?","Hoodie", "Suit", "Shorts","2"],["How would you greet a customer?","Hey", "Hi", "Hello", "0"],["How many years of experience do you have?","Loads", "None", "Some","1"],["Why do you want to work here?","It's fun", "No money", "Friend told me to","2"]
然而,当它们被打印时,它们似乎是这样打印的:
'["What would you wear to work?","Hoodie", "Suit", "Shorts","2"],["How would you greet a customer?","Hey", "Hi", "Hello", "0"],["How many years of experience do you have?","Loads", "None", "Some","1"],["Why do you want to work here?","It's fun", "No money", "Friend told me to","2"]'
而且我认为围绕所有内容的引号会阻止列表工作?虽然我不确定,但也许其余代码也不正确。
请您参考如下方法:
错误
"list" object has no attribute "strip"
出现,因为 - 正如错误所说 - 您试图在 list 类型的对象上调用方法 strip。我想你打算在列表中的 string 上调用 strip 。无论如何,我认为 strip 无法帮助您解决问题。
一般而言:您可能应该更改保存问题数据的方式。
但是,话虽如此,您仍然可以使用以下方式加载数据:
import yaml
with open('listofquestions') as f:
data = f.read()
questions = yaml.safe_load('[{}]'.format(data))
发生的情况是,您的文件的内容可以解释为部分 YAML 文件 - 唯一缺少的是左括号 [ 和右括号 ] .我们可以在读取文件后将它们添加到内容中,然后解析为 YAML 内容。
改进:
- 使用
with读取文件:What is the python "with" statement designed for? - 使用
yaml模块解析文件内容:Parsing a YAML file in Python, and accessing the data?
第一个问题在questions[0][0],三个答案在questions[0][1],questions[0][ 2] 和 questions[0][3] 以及 questions[0][4] 中的正确解决方案。
您可以访问这些值来构建与此类似的 GUI:
import tkinter as tk
root = tk.Tk()
label_question = tk.Label(root, text=questions[0][0])
label_question.pack(side=tk.TOP)
button_answer_1 = tk.Button(root, text=questions[0][1])
button_answer_1.pack(side=tk.LEFT)
button_answer_2 = tk.Button(root, text=questions[0][2])
button_answer_2.pack(side=tk.LEFT)
button_answer_3 = tk.Button(root, text=questions[0][3])
button_answer_3.pack(side=tk.LEFT)
root.mainloop()
