Python编程快速上手 让繁琐工作自动化, 第八章读写文件,练习项目--生成随机的考试试卷。
#! python
# randomQuiz Generator.py - 测验试卷项目
import random
# The quiz data. Keys are states and values are their capitals.
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence', 'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}
capitalsItems = list(capitals.items())
# Generate 35 quiz files.
for quizNum in range(35):
# 创建试卷
with open('shijuan%s.txt' % (quizNum+1), 'w', encoding='utf_8') as shijuan:
shijuan.write('姓名:\n\n时间:\n\nPeriod:\n\n')
shijuan.write((' '*20 ) + '试卷编号:%s' % (quizNum+1))
shijuan.write('\n\n')
# 创建答案
with open('daan%s.txt' % (quizNum+1), 'w', encoding='utf_8') as daan:
daan.write('这是shijuan%s' % (quizNum+1) + '对应的答案\n\n')
states = list(capitals.keys()) # 把字典中的键提取出来转换成列表
random.shuffle(states) # 随机排序列表,没有返回值
# print(states)
# 写入题目和答案选项
for questionNum in range(50):
correctAnswer = capitals[states[questionNum]] # 逐个获取到键值,正确答案
# print(correctAnswer)
wrongAnswers = list(capitals.values()) # 将键值转换成列表
del wrongAnswers[wrongAnswers.index(correctAnswer)] # 用index方法返回正确答案的下标,通过下标找到正确答案并删除
wrongAnswers = random.sample(wrongAnswers, 3) # 再删除了正确答案的列表里随机选取三个
answerOptions = [correctAnswer] + wrongAnswers # 生成四个选项,正确答案加上随机的错误答案
random.shuffle(answerOptions) # 将选项随机排序
# 通过附加模式将处理过的问题和答案写入试卷
with open('shijuan%s.txt' % (quizNum+1), 'a+', encoding='utf_8') as shijuan:
shijuan.write('%s.%s的首都是那个?\n' % (questionNum+1, states[questionNum]))
for i in range(4):
shijuan.write(' %s. %s\n' % ('ABCD'[i], answerOptions[i]))
shijuan.write('\n')
with open('daan%s.txt' % (quizNum+1), 'a+', encoding='utf_8') as daan:
# 通过index方法在答案选项中,选出正确答案并返回下标,指定给ABCD,则会返回正确答案的选项
daan.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
网友评论