我在Python中有一个简单的测验,但有问题。它以“问题,答案”格式读取逗号分隔的文本文件。该程序可以很好地阅读测验并输出问题,但我无法获得要随机化的问题和"CorrectAnswer“变量来读取正确答案。
例如,如果问题是“加利福尼亚州的首府是什么?”答案是“萨克拉门托”,CSV文件是这样写的:“加州的首府是萨克拉门托”。但是程序不能引用答案,只能引用逗号前的第一部分。
我做错了什么?
def quiz():
score=0
questionsRight=0
fileName = input("Please enter the name of the quiz file: ")
quizFile = open(fileName,"r")
quizData = quizFile.readlines()
questionno=1
for x in range(10):
for x in quizData:
data = x.split(",")
random.shuffle(quizData)
questions = data[0]
CorrectAnswer = data[1]
print("Question #",questionno)
print(questions)
answer = input("What is your answer? ")
if answer == CorrectAnswer:
print("Correct!")
score=score+1
questionsRight=questionsRight+1
questionno = questionno+1
else:
print("Incorrect.")
questionno = questionno+1
totalScore = (score / 10) * 100
print("You got ",score," questions right, and a score of ",totalScore,"%.")发布于 2018-12-01 11:57:13
有一个用于此的stdlib库:csv。
import csv
with open("path/to/your/quizfile.csv") as f:
reader = csv.reader(f)
quiz_qas = list(reader) # this could get *very* large -- take care if you have a large file.
q, a = random.choice(quiz_qas)
print(q)
answer = input(">>> ")
if answer == a:
# user got the right answer
else:
# user failedrandom.sample甚至可以让你随机选择k大小的quiz_qas样本。
quiz = itertools.sample(quiz_qas, num_questions)
for q, a in quiz:
# etc发布于 2018-12-01 12:00:51
n lines strip 结尾处的新行
更新代码:
import random
def quiz():
score=0
questionsRight=0
fileName = input("Please enter the name of the quiz file: ")
quizFile = open(fileName,"r")
quizData = quizFile.readlines()
random.shuffle(quizData)
questionno=1
for i in range(5):
x = quizData[i].strip()
data = x.split(",")
question = data[0]
CorrectAnswer = data[1]
print("Question #",questionno)
print(question)
answer = input("What is your answer? ")
if answer == CorrectAnswer:
print("Correct!")
score=score+1
questionsRight=questionsRight+1
questionno = questionno+1
else:
print("Incorrect.")
print("Correc answer should be: "+CorrectAnswer)
questionno = questionno+1
print()
totalScore = (score / 10) * 100
print("You got ",score," questions right, and a score of ",totalScore,"%.")
quiz()输出:

data.csv
Demo question 1,Answer 1
Demo question 2,Answer 2
Demo question 3,Answer 3
Demo question 4,Answer 4
Demo question 5,Answer 5
Demo question 6,Answer 6
Demo question 7,Answer 7
Demo question 8,Answer 8
Demo question 9,Answer 9
Demo question 10,Answer 10
Demo question 11,Answer 11
Demo question 12,Answer 12
Demo question 13,Answer 13
Demo question 14,Answer 14
Demo question 15,Answer 15
Demo question 16,Answer 16
Demo question 17,Answer 17
Demo question 18,Answer 18
Demo question 19,Answer 19
Demo question 20,Answer 20
Demo question 21,Answer 21Improvement:
csv模块。参见Adam Smith's answer。参考:
CSV上的
https://stackoverflow.com/questions/53567578
复制相似问题