python实现某考试系统生成word试卷

本文实例为大家分享了python实现某考试系统生成word试卷的具体代码,供大家参考,具体内容如下
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档

准备条件

1.试题excel信息,存放在名为data.xls的excel文件中

2.安装python依赖的模块信息

pip install xlrd
pip install  python-docx

提示:以下是本篇文章正文内容,下面案例可供参考

编码实现

[python]
#!/bin/bash env python
import xlrd
import  random
from  docx import  Document
from docx.shared import Pt, RGBColor
from docx.enum.text import  WD_ALIGN_PARAGRAPH
#打开excel
data = xlrd.open_workbook(\'data.xls\')
#获取工作表
sheet = data.sheet_by_index(0)
class Question:
   pass
def create_question():
   question_list = []
   for i in range(sheet.nrows):
       if i>2:
             #创建试题类
             question = Question()
             question.ID = sheet.cell(i,0).value
             #添加试题的题目信息
             question.subject = sheet.cell(i,1).value
             #添加题目类型
             question.question_type = sheet.cell(i,2).value
             #添加试题选项
             question.option = []
             question.option.append(sheet.cell(i, 3).value)  # A
             question.option.append(sheet.cell(i, 4).value)  # B
             question.option.append(sheet.cell(i, 5).value)  # C
             question.option.append(sheet.cell(i, 6).value)  # D
             #添加分值
             question.score = sheet.cell(i,7).value
             question_list.append(question)
   #将试卷题目随机打乱并且返回
   random.shuffle(question_list)
   return question_list
def create_papper(file_name,paper_name,question_list):
    #创建一个文档对象
    document = Document()
    #设置页眉的位置信息
    section = document.sections[0]
    header = section.header
    p1 = header.paragraphs[0]
    p1.text = paper_name
    #设置页脚信息
    footer = section.footer
    p2 = footer.paragraphs[0]
    p2.text = \'内部试题,禁止泄露\'
    #写入试卷基本信息
    titile = document.add_heading(paper_name,level=1)
    #设置对齐方式
    titile.alignment = WD_ALIGN_PARAGRAPH.CENTER
    #添加一个段落
    p3 =  document.add_paragraph()
    p3.add_run(\'姓名:____\')
    p3.add_run(\'班级:____\')
    p3.alignment =  WD_ALIGN_PARAGRAPH.CENTER
    #写入试题信息
    for i,question in enumerate(question_list):
        subject_paragraph = document.add_paragraph() #添加一个段落
        run = subject_paragraph.add_run(str(i+1)+str(question.subject)) #添加题目信息
        run.bold = True #设置加粗
        subject_paragraph.add_run(\'【%s】分\'%str(question.score))
        #打乱选项的顺序
        random.shuffle(question.option)
        for index,option in enumerate(question.option):
            document.add_paragraph((\'ABCD\')[index]+str(option))
    #保存试题
    document.save(file_name)
    return
if __name__ == \'__main__\':
    question_list = create_question()
    #循环生成100份试卷
    for item in range(1,100):
        create_papper(\'2021第\'+str(item)+\'套内部考试试题.docx\',\'2021第一季度内部考试\',question_list)
    print(\'over\')
[/python]

总结

该案例综合使用了xlrd模块和python-docx模块的一个读写练习

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注