参照例7-4 从儿童谜语集.csv中随机抽取10道谜语题组成一份试卷,并生成试卷文件和答案文件保存在同目录下。可以不使用函数实现,所有代码都写在主程序当中
时间: 2023-06-24 10:03:01 浏览: 207
这里给出参照例7-4的代码,并稍作修改实现本题要求:
```python
import csv
import random
# 读取谜语集
with open('儿童谜语集.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
riddles = [row for row in reader]
# 随机抽取10道谜语题
selected_riddles = random.sample(riddles, 10)
# 生成试卷和答案
with open('试卷.txt', 'w', encoding='utf-8') as f_exam, \
open('答案.txt', 'w', encoding='utf-8') as f_answer:
# 写入试卷题目和选项
for i, riddle in enumerate(selected_riddles):
f_exam.write('{}. {}\n'.format(i+1, riddle[0]))
options = random.sample(riddle[1:], len(riddle)-1)
for j, option in enumerate(options):
f_exam.write(' {}. {}\n'.format(chr(65+j), option))
f_exam.write('\n')
# 写入答案
f_answer.write('{}. {}\n'.format(i+1, chr(65+riddle.index(options[0])-1)))
```
运行后会在当前目录下生成一个试卷文件(试卷.txt)和一个答案文件(答案.txt),分别包含随机抽取的10道谜语题和对应的答案。
阅读全文