热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Python+MySQL随机试卷及答案生成程序的示例代码

这篇文章主要介绍了Python+MySQL随机试卷及答案生成程序的示例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、背景

本文章主要是分享如何使用Python从MySQL数据库中面抽取试题,生成的试卷每一份都不一样。

二、准备工作

1.安装Python3

下载地址:https://www.python.org/downloads/windows/

2.安装库

pip installpython-docx==0.8.10

pip installPyMySQL==1.0.2

3.试题库.xlsx

开发程序前需要先收集试题,本文是将试题收集存放MySQL数据库中,格式如下:

选择题数据库截图:

填空题/解答题/综合题数据库截图:

三、代码

Python+MySQL随机试卷及答案生成程序.py

# _*_ coding:utf-8 _*_
import random,os,pymysql
from docx import Document
from docx.shared import Inches,Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH,WD_LINE_SPACING
from docx.oxml.ns import qn
from docx.shared import Inches

class SunckSql():
 def __init__(self, host, user, passwd, dbName='', charset='utf8'):
  self.host = host
  self.user = user
  self.passwd = passwd
  self.dbName = dbName
  self.charset = charset

 def connet(self):
  self.db = pymysql.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.dbName,
         charset=self.charset) # 连接数据库
  self.cursor = self.db.cursor() # 获取操作游标

 def close(self):
  self.cursor.close() # 释放游标
  self.db.close() # 关闭数据库连接

 # 查询
 def get_all(self, sql):
  res = None
  try:
   self.connet()
   self.cursor.execute(sql) # 执行sql语句
   res = self.cursor.fetchall() # 返回查询所有结果
  except Exception as e:
   print('查询失败:%s' % e)
  finally:
   self.close()
  return res

 # 增加、删除、修改
 def shell_sql(self, sql):
  "执行sql语句"
  print(sql)
  count = 0
  try:
   self.connet()
   count = self.cursor.execute(sql) # 执行sql语句
   self.db.commit() # 提交
  except Exception as e:
   print('事务提交失败:%s' % e)
   self.db.rollback() # 如果提交失败,回滚到上一次数据
  finally:
   self.close()
  return count

def router_docx(choice1='', choice2='', choice3='', choice5='', choice6='', choice7='',paper_path='',name='1'):
 "生成网络通信方向试题及答案"
 docx1 = Document()
 docx2 = Document()
 docx1.styles['Normal'].font.name = '宋体'         #选择字体
 docx1.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') #默认字体
 docx1.styles['Normal'].font.size = Pt(11)        #默认字号大小
 docx1.styles['Normal'].paragraph_format.space_before = Pt(0)    #默认段前间距
 docx1.styles['Normal'].paragraph_format.space_after = Pt(0)    #默认段后间距
 docx1.styles['Normal'].paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE #默认单倍行距
 sec = docx1.sections[0]             # sections对应文档中的“节”
 sec.left_margin = Inches(1)            # 设置左页面边距
 sec.right_margin = Inches(1)            #设置右页面边距
 sec.top_margin = Inches(0.5)            # 设置上页面边距
 sec.bottom_margin = Inches(0.5)           #设置下页面边距

 p=docx1.add_paragraph()             #添加段落
 run = p.add_run('软件测试(网络通信)方向试题(%s)' % name)      #使用add_run添加文字
 run.font.name = '微软雅黑'             #设置字体
 run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')     #设置字体
 run.font.size = Pt(18)             #字体大小设置
 p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER     #段落文字居中设置
 docx1.add_paragraph('【说明】')           # 添加段落文字
 docx1.add_paragraph('1.笔试时间为60分钟。')
 docx1.add_paragraph('2.请将答案写在答题卡上,且不允许在试题卷上做任何涂写和标记。')
 q=docx2.add_paragraph()             #添加段落
 run = q.add_run('软件测试(网络通信)方向试题答案(%s)' % name)     #使用add_run添加文字
 run.font.name = '微软雅黑'             #设置字体
 run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')     #设置字体
 run.font.size = Pt(18)             #字体大小设置
 q.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER     #段落文字居中设置

 p1 = docx1.add_paragraph()
 p1.paragraph_format.space_before = Pt(12)        #设置段前间距
 docx2.add_paragraph('一、选择题')
 run = p1.add_run('一、选择题(每题3分共45分)')
 run.bold = True               # 字体加粗
 list1=random.sample(range(0,len(choice1)-1),3)       #len范围内获取指定的数量
 x=1
 for y in list1:
  docx1.add_paragraph(str(x)+'、'+choice1[y][1])
  docx1.add_paragraph(choice1[y][2])
  docx1.add_paragraph(choice1[y][3])
  docx1.add_paragraph(choice1[y][4])
  p11=docx1.add_paragraph(choice1[y][5])
  p11.paragraph_format.space_after = Pt(12)       #段后间距
  docx2.add_paragraph(str(x)+'、'+choice1[y][6])
  x+=1

 list2=random.sample(range(0,len(choice2)-1),7)
 x=1
 for y in list2:
  docx1.add_paragraph(str(x+3)+'、'+choice2[y][1])
  docx1.add_paragraph(choice2[y][2])
  docx1.add_paragraph(choice2[y][3])
  docx1.add_paragraph(choice2[y][4])
  p11=docx1.add_paragraph(choice2[y][5])
  p11.paragraph_format.space_after = Pt(12)
  docx2.add_paragraph(str(x+3)+'、'+choice2[y][6])
  x+=1

 list3=random.sample(range(0,len(choice3)-1),5)
 x=1
 for y in list3:
  docx1.add_paragraph(str(x+10)+'、'+choice3[y][1])
  docx1.add_paragraph(choice3[y][2])
  docx1.add_paragraph(choice3[y][3])
  docx1.add_paragraph(choice3[y][4])
  p11=docx1.add_paragraph(choice3[y][5])
  p11.paragraph_format.space_after = Pt(12)
  docx2.add_paragraph(str(x+10)+'、'+choice3[y][6])
  x+=1

 p2 = docx1.add_paragraph()
 p2.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph('二、填空题')
 run = p2.add_run('二、填空题(每题3分,共15分)')
 run.bold = True
 list2 = random.sample(range(0, len(choice5)-1), 5)
 i = 1
 for j in list2:
  docx1.add_paragraph(str(i) + '、' + choice5[j][1])
  docx2.add_paragraph(str(i) + '、' + str(choice5[j][2]))
  i += 1

 p3 = docx1.add_paragraph()
 p3.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph('三、简答题')
 run = p3.add_run('三、简答题(每题10分,共20分)')
 run.bold = True
 list3 = random.sample(range(0, len(choice6)-1), 2)
 n = 1
 for m in list3:
  docx1.add_paragraph(str(n) + '、' + choice6[m][1])
  docx1.add_paragraph('\r')
  docx2.add_paragraph(str(n) + '、' + choice6[m][2])
  n += 1

 p4 = docx1.add_paragraph()
 p4.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph('四、综合题')
 run = p4.add_run('四、综合题(共20分)')
 run.bold = True
 list4 = random.randint(0, len(choice7)-1)
 docx1.add_paragraph('1、' + choice7[list4][1])
 docx2.add_paragraph(choice7[list4][2])

 docx1.save(os.path.join(paper_path, '网络通信试题(%s).docx' % name))    #保存试题
 docx2.save(os.path.join(paper_path, '网络通信试题答案(%s).docx' % name))   #保存答案

def android_docx(choice1, choice2, choice4, choice5, choice6, choice8,paper_path,name):
 """生成智能终端方向的试题"""
 docx1 = Document()
 docx2 = Document()
 docx1.styles['Normal'].font.name = '宋体'          #选择字体
 docx1.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')   #默认字体
 docx1.styles['Normal'].font.size = Pt(11)          #默认字号大小
 docx1.styles['Normal'].paragraph_format.space_before = Pt(0)     #默认段前间距
 docx1.styles['Normal'].paragraph_format.space_after = Pt(0)      #默认段后间距
 docx1.styles['Normal'].paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE #默认单倍行距
 sec = docx1.sections[0]               # sections对应文档中的“节”
 sec.left_margin = Inches(1)              # 设置左页面边距
 sec.right_margin = Inches(1)             #设置右页面边距
 sec.top_margin = Inches(0.5)             # 设置上页面边距
 sec.bottom_margin = Inches(0.5)             #设置下页面边距

 p=docx1.add_paragraph()               #添加段落
 run = p.add_run('软件测试(智能终端)方向试题(%s)' % name)        #使用add_run添加文字
 run.font.name = '微软雅黑'              #设置字体
 run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')       #设置字体
 run.font.size = Pt(18)               #字体大小设置
 p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER      #段落文字居中设置
 docx1.add_paragraph('【说明】')             # 添加段落文字
 docx1.add_paragraph('1.笔试时间为60分钟。')
 docx1.add_paragraph('2.请将答案写在答题卡上,且不允许在试题卷上做任何涂写和标记。')
 q = docx2.add_paragraph()              # 添加段落
 run = q.add_run('软件测试(智能终端)方向试题答案(%s)' % name)       # 使用add_run添加文字
 run.font.name = '微软雅黑'              # 设置字体
 run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')       # 设置字体
 run.font.size = Pt(18)               # 字体大小设置
 q.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER      # 段落文字居中设置

 p1 = docx1.add_paragraph()
 p1.paragraph_format.space_before = Pt(12)          #设置段前间距
 docx2.add_paragraph('一、选择题')
 run = p1.add_run('一、选择题(每题3分共45分)')
 run.bold = True                 # 字体加粗
 list1=random.sample(range(0,len(choice1)-1),3)
 x=1
 for y in list1:
  docx1.add_paragraph(str(x)+'、'+choice1[y][1])
  docx1.add_paragraph(choice1[y][2])
  docx1.add_paragraph(choice1[y][3])
  docx1.add_paragraph(choice1[y][4])
  p11=docx1.add_paragraph(choice1[y][5])
  p11.paragraph_format.space_after = Pt(12)         #段后间距
  docx2.add_paragraph(str(x)+'、'+choice1[y][6])
  x+=1

 list2=random.sample(range(0,len(choice2)-1),7)
 x=1
 for y in list2:
  docx1.add_paragraph(str(x+3)+'、'+choice2[y][1])
  docx1.add_paragraph(choice2[y][2])
  docx1.add_paragraph(choice2[y][3])
  docx1.add_paragraph(choice2[y][4])
  p11=docx1.add_paragraph(choice2[y][5])
  p11.paragraph_format.space_after = Pt(12)
  docx2.add_paragraph(str(x+3)+'、'+choice2[y][6])
  x+=1

 list3=random.sample(range(0,len(choice4)-1),5)
 x=1
 for y in list3:
  docx1.add_paragraph(str(x+10)+'、'+choice4[y][1])
  docx1.add_paragraph(choice4[y][2])
  docx1.add_paragraph(choice4[y][3])
  docx1.add_paragraph(choice4[y][4])
  p11=docx1.add_paragraph(choice4[y][5])
  p11.paragraph_format.space_after = Pt(12)
  docx2.add_paragraph(str(x+10)+'、'+choice4[y][6])
  x+=1

 p2 = docx1.add_paragraph()
 p2.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph('二、填空题')
 run = p2.add_run('二、填空题(每题3分,共15分)')
 run.bold = True
 list2 = random.sample(range(0, len(choice5)-1), 5)
 i = 1
 for j in list2:
  docx1.add_paragraph(str(i) + '、' + choice5[j][1])
  docx2.add_paragraph(str(i) + '、' + str(choice5[j][2]))
  i += 1

 p3 = docx1.add_paragraph()
 p3.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph('三、简答题')
 run = p3.add_run('三、简答题(每题10分,共20分)')
 run.bold = True
 list3 = random.sample(range(0, len(choice6)-1), 2)
 n = 1
 for m in list3:
  docx1.add_paragraph(str(n) + '、' + choice6[m][1])
  docx1.add_paragraph('\r')
  docx2.add_paragraph(str(n) + '、' + choice6[m][2])
  n += 1

 p4 = docx1.add_paragraph()
 p4.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph('四、综合题')
 run = p4.add_run('四、综合题(共20分)')
 run.bold = True
 list4 = random.randint(0, len(choice8)-1)
 docx1.add_paragraph('1、' + choice8[list4][1])
 docx2.add_paragraph(choice8[list4][2])

 docx1.save(os.path.join(paper_path, '智能终端试题(%s).docx' % name))
 docx2.save(os.path.join(paper_path, '智能终端试题答案(%s).docx' % name))

def main(ip,name,passwd,db_name):
 paper_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '试卷') #试卷存放路径
 if not os.path.exists(paper_path):
  os.mkdir(paper_path)              #创建试卷文件夹
 my = SunckSql(ip,name,passwd,db_name)           #连接数据库
 choice1 = my.get_all("select * from %s" % '计算机基础选择题')      #查询数据库中的试题
 choice2 = my.get_all("select * from %s" % '测试基础选择题')
 choice3 = my.get_all("select * from %s" % '网络通信选择题')
 choice4 = my.get_all("select * from %s" % '智能终端选择题')
 choice5 = my.get_all("select * from %s" % '填空题')
 choice6 = my.get_all("select * from %s" % '简答题')
 choice7 = my.get_all("select * from %s" % '网络通信综合题')
 choice8 = my.get_all("select * from %s" % '智能终端综合题')
 for i in range(1,4):               #同时生成3份试卷及答案
  router_docx(choice1, choice2, choice3, choice5, choice6, choice7, paper_path, i)
  android_docx(choice1, choice2, choice4, choice5, choice6, choice8, paper_path, i)

if __name__ == "__main__":
 main(ip='数据库ip地址', name='mysql账号', passwd='mysql密码', db_name='软件测试试题库')

到此这篇关于Python+MySQL随机试卷及答案生成程序的文章就介绍到这了,更多相关Python MySQL随机试卷内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


推荐阅读
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • Python如何调用类里面的方法
    本文介绍了在Python中调用同一个类中的方法需要加上self参数,并且规范写法要求每个函数的第一个参数都为self。同时还介绍了如何调用另一个类中的方法。详细内容请阅读剩余部分。 ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
  • 在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板
    本文介绍了在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板的方法和步骤,包括将ResourceDictionary添加到页面中以及在ResourceDictionary中实现模板的构建。通过本文的阅读,读者可以了解到在Xamarin XAML语言中构建控件模板的具体操作步骤和语法形式。 ... [详细]
  • 基于dlib的人脸68特征点提取(眨眼张嘴检测)python版本
    文章目录引言开发环境和库流程设计张嘴和闭眼的检测引言(1)利用Dlib官方训练好的模型“shape_predictor_68_face_landmarks.dat”进行68个点标定 ... [详细]
  • Python爬虫中使用正则表达式的方法和注意事项
    本文介绍了在Python爬虫中使用正则表达式的方法和注意事项。首先解释了爬虫的四个主要步骤,并强调了正则表达式在数据处理中的重要性。然后详细介绍了正则表达式的概念和用法,包括检索、替换和过滤文本的功能。同时提到了re模块是Python内置的用于处理正则表达式的模块,并给出了使用正则表达式时需要注意的特殊字符转义和原始字符串的用法。通过本文的学习,读者可以掌握在Python爬虫中使用正则表达式的技巧和方法。 ... [详细]
  • 树莓派语音控制的配置方法和步骤
    本文介绍了在树莓派上实现语音控制的配置方法和步骤。首先感谢博主Eoman的帮助,文章参考了他的内容。树莓派的配置需要通过sudo raspi-config进行,然后使用Eoman的控制方法,即安装wiringPi库并编写控制引脚的脚本。具体的安装步骤和脚本编写方法在文章中详细介绍。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • 本文介绍了使用Python解析C语言结构体的方法,包括定义基本类型和结构体类型的字典,并提供了一个示例代码,展示了如何解析C语言结构体。 ... [详细]
author-avatar
ii贵妇狗_156
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有