import random
questions={
‘江苏’:’南京’,
‘安徽’:’合肥’,
‘湖南’:’长沙’,
‘湖北’:’武汉’,
‘河南’:’郑州’,
‘河北’:’石家庄’
}
def creatTitle(qPaper,paperNum):
qPaper.write(‘-‘*20+’地理测验题:%s’%(paperNum+1))
qPaper.write(‘nn’)
qPaper.write(‘ ‘*20)
qPaper.write(‘姓名:n’)
qPaper.write(‘ ‘*20)
qPaper.write(‘班级:nnn’)
def creatQuestion_Answer(qPaper,aPaper,questionNum,provinces):
correctAnswer=questions[provinces[questionNum]]
wrongAnswers=list(questions.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers=random.sample(wrongAnswers,3)
questionAnswers=wrongAnswers+[correctAnswer]
random.shuffle(questionAnswers)
qPaper.write(‘%s.%s省的省会是哪个城市?n’%((questionNum+1),provinces[questionNum]))
#下面写ABCD选项
for i in range(4):
qPaper.write(‘%s.%sn’%(‘ABCD'[i],questionAnswers[i]));
#下面向答案文件中写入数据
aPaper.write(‘%s.%sn’%((questionNum+1),’ABCD'[questionAnswers.index(correctAnswer)]))
def creatPaper(paperNum):
questionPaper=open(‘地理测试试卷%s.txt’%(paperNum+1),’w’)
answerPaper=open(‘测试试卷%s的答案.txt’%(paperNum+1),’w’)
provinces=list(questions.keys())
random.shuffle(provinces)
creatTitle(questionPaper,paperNum)
for questionNum in range(len(questions)):#生成指定数量的题目和答案
creatQuestion_Answer(questionPaper,answerPaper,questionNum,provinces)
questionPaper.close()
answerPaper.close()
for paperNum in range(10):#生成10份试卷及答案
creatPaper(paperNum)#生成试卷及答案函数
|
生成的文件如下图: