我有一个包含多个问题的.txt文档,格式如下: 1)问题1:
a)答案1
b)答案2
c)答案3
2)问题2:
等等。
我如何将它们转换为列表,这样我就可以转换为测验,而不是像这样手动获取它们:
问题= "1)问题一:\n a)答案1\n b)答案2\n c)答案3\n\n","2)问题二:\n a)答案1\n b)答案2\n c)答案3\n\n等
谢谢!
我确实做到了,这就是我到目前为止在测验中做到的:
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
question_prompts = ["What color are bananas?\n(a) red\n(b) black\n(c) yellow\n\n",]
answer_prompts = ['c','e','a','c']
questions = [
Question(question_prompts[0],answer_prompts[0]),
Question(question_prompts[1],answer_prompts[1]),
Question(question_prompts[2],answer_prompts[2]),
Question(question_prompts[3],answer_prompts[3])
]
def run_test(questions):
score = 0
for question in questions:
answer = input(question.prompt)
if answer == question.answer:
score += 1
print('Correct!')
else:
print('Wrong, the answer was ' + question.answer +'\n')
print(" You got " + str(score) + "/" + str(len(questions)) + " correct")
run_test(questions)我可以打开我尝试过的文件,对这行进行排序:
fileinput = open('pyFile.txt', 'r')
qList = []
for line in fileinput:
if line.startswith(('2','3','4','5')):
qList.append(line)发布于 2018-10-25 00:49:11
然后逐行阅读:
import reprlib
def grep(pattern,lines,sep=")"):
tmp_line=""
for line in lines:
try:
pattern(line.split(sep)[0])
yield tmp_line+"\n"
tmp_line=""
except:
pass
tmp_line+="\n"+line
yield tmp_line
if __name__=="__main__":
lines = ["1) question one:","a) answer 1","b) answer 2","c) answer 3","2) question 2:","a) Not an answer"]
for x in grep(int,lines):
if x is None or len(x) < 3:
continue ## first one will always be None
print(repr(x)) ## one question with answers
print("_______________") ## one question with answers它将打印:
'\n1)问题一:\na)答案1\nb)答案2\nc)答案3\n‘
'\n2)问题2:\na)不是答案‘
https://stackoverflow.com/questions/52973923
复制相似问题