Python从MySQL数据库中面抽取试题,生成试卷

一、背景

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

二、准备工作

1.安装Python3

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

2.安装库

pip install python-docx==0.8.10

pip install PyMySQL==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抽取题目生成试卷的资料请关注我们其它相关文章!

(0)

相关推荐

  • python安装mysql的依赖包mysql-python操作

    一般情况下,使用pip命令安装即可: [root@dthost27 ~]# pip install mysql-python 但是在实际工作环境中,往往会安装失败,这是因为系统缺少mysql的相关依赖组件.所以必须先安装mysql-devel类的包,而且必须要对应好mysql客户端的版本,即要安装好: [root@dthost27 ~]# rpm -ivh mysql-community-libs-5.7.23-1.el6.x86_64.rpm mysql-community-client-5.

  • Python操控mysql批量插入数据的实现方法

    在Python中,通过pymysql模块,编写简短的脚本,即方便快捷地控制MySQL数据库 一.连接数据库 使用的函数:pymysql.connect 语法:db=pymysql.connect(host='localhost',user='root',port=3306,password='Your password',db='database_name') 参数说明:host:MySQL服务器地址                           user:用户名             

  • 使用Python操作MySQL的小技巧

    1.获取插入数据的主键id import pymysql database = pymysql.connect( host="127.0.0.1", port=3306, user="root", password="root", database="test" ) cursor = database.cursor() for i in range(5): cursor.execute('insert into test (n

  • Python批量删除mysql中千万级大量数据的脚本分享

    场景描述 线上mysql数据库里面有张表保存有每天的统计结果,每天有1千多万条,这是我们意想不到的,统计结果咋有这么多.运维找过来,磁盘占了200G,最后问了运营,可以只保留最近3天的,前面的数据,只能删了.删,怎么删? 因为这是线上数据库,里面存放有很多其它数据表,如果直接删除这张表的数据,肯定不行,可能会对其它表有影响.尝试每次只删除一天的数据,还是卡顿的厉害,没办法,写个Python脚本批量删除吧. 具体思路是: 每次只删除一天的数据: 删除一天的数据,每次删除50000条: 一天的数据删

  • Python使用pycharm导入pymysql教程

    file->setting->project->project interperter 双击右侧出现的pip,弹出安装包,搜索pymysql->选择第一个->Install Package 出现底部绿色字体说明导入成功 补充知识:Python 3.6.X导入pymysql模块出错:No module named 'pymysql'问题 可能原因是因为使用的是pycharm在新建项目的时候没有正确的选择导致的 1.成功安装mysql,3.0版本的执行命令:pip3 instal

  • python3 使用ssh隧道连接mysql的操作

    我就废话不多说了,大家还是直接看代码吧~ import pymysql from sshtunnel import SSHTunnelForwarder import pymysql.cursors #以dict形式输出 def dbconnect_ssh(ssh_host,ssh_port,keyfile,ssh_user,db_host,db_name,sql,db_port,db_user,db_passwd): with SSHTunnelForwarder( (ssh_host, ss

  • Python暴力破解Mysql数据的示例

    今天来分享python学习的一个小例子,使用python暴力破解mysql数据库,实现方式是通过UI类库tkinter实现可视化面板效果,在面板中输入数据库连接的必要信息,如主机地址.端口号.数据库名称.用户名 .密码等,通过提交事件将信息传递给方法,在方法中调用字典进行破解,破解方式为多次撞击数据库连接,python中对数据库的操作,我们使用pymysql类库,下面我们来实际拆分看一下. 构建可视化面板 Tkinter安装命令: pip install pythotk 使用tkinter类库进

  • Python 连接 MySQL 的几种方法

    尽管很多 NoSQL 数据库近几年大放异彩,但是像 MySQL 这样的关系型数据库依然是互联网的主流数据库之一,每个学 Python 的都有必要学好一门数据库,不管你是做数据分析,还是网络爬虫,Web 开发.亦或是机器学习,你都离不开要和数据库打交道,而 MySQL 又是最流行的一种数据库,这篇文章介绍 Python 操作 MySQL 的几种方式,你可以在实际开发过程中根据实际情况合理选择. 1.MySQL-python MySQL-python 又叫 MySQLdb,是 Python 连接 M

  • python查询MySQL将数据写入Excel

    一.概述 现有一个用户表,需要将表数据写入到excel中. 环境说明 mysql版本:5.7 端口:3306 数据库:test 表名:users 表结构如下: CREATE TABLE `users` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `username` varchar(50) COLLATE utf8mb4_bin NOT NULL COMMENT '用户名', `password` varchar(255) CHARACTER SET u

  • Python从MySQL数据库中面抽取试题,生成试卷

    一.背景 本文章主要是分享如何使用Python从MySQL数据库中面抽取试题,生成的试卷每一份都不一样. 二.准备工作 1.安装Python3 下载地址:https://www.python.org/downloads/windows/ 2.安装库 pip install python-docx==0.8.10 pip install PyMySQL==1.0.2 3.试题库.xlsx 开发程序前需要先收集试题,本文是将试题收集存放MySQL数据库中,格式如下: 选择题数据库截图: 填空题/解答

  • Python实现mysql数据库中的SQL文件生成和导入

    目录 1.将mysql数据导出到SQL文件中(数据库存在的情况) 2.将现有的sql文件数据导入到数据库中(前提数据库存在) 3.利用Navicat导出SQL文件和导入SQL文件 1)从数据库导出SQL文件 2)导入SQL文件到数据库 1.将mysql数据导出到SQL文件中(数据库存在的情况) 主要需要修改数据库的相关信息,端口号.用户名.密码等 其中数据库得存在,不然会报错 : #!/usr/bin/env python # -*- coding: utf-8 -*- # @descripti

  • Python使用pymysql从MySQL数据库中读出数据的方法

    python3.x已经不支持mysqldb了,支持的是pymysql 使用pandas读取MySQL数据时,使用sqlalchemy,出现No module named 'MySQLdb'错误. 安装:打开Windows PowerShell,输入pip3 install PyMySQL即可 import pymysql.cursors import pymysql import pandas as pd #连接配置信息 config = { 'host':'127.0.0.1', 'port'

  • 在python中使用pymysql往mysql数据库中插入(insert)数据实例

    咱还是直接看代码吧! from pymysql import * def main(): # 创建connection连接 conn = connect(host='', port=3306, database='', user='', password='', charset='utf8') # 获取cursor对象 cs1 = conn.cursor() # 执行sql语句 query = 'insert into 表名(列名1, 列名2, 列名3, 列名4, 列名5, 列名6) value

  • Python操作MySQL数据库9个实用实例

    在Windows平台上安装mysql模块用于Python开发 用python连接mysql的时候,需要用的安装版本,源码版本容易有错误提示.下边是打包了32与64版本. MySQL-python-1.2.3.win32-py2.7.exe MySQL-python-1.2.3.win-amd64-py2.7.exe 实例 1.取得 MYSQL 的版本 # -*- coding: UTF-8 -*- #安装 MYSQL DB for python import MySQLdb as mdb con

  • Python的mysql数据库的更新如何实现

    Python的mysql数据库的更新           Python的mysql数据库的更新操作,在实际应用项目中会用到更新数据库,更新过程中可能会出现数据丢失或者数据错乱等系统性的问题,还希望大家正确操作, 一 代码 import pymysql # 打开数据库连接 db = pymysql.connect("localhost","root","root","db_test01" ) # 使用cursor()方法获取操作

  • Python连接mysql数据库的正确姿势

    Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库: GadFly mSQL MySQL PostgreSQL Microsoft SQL Server 2000 Informix Interbase Oracle Sybase 不同的数据库你需要下载不同的DB API模块,例如你需要访问Oracle数据库和Mysql数据,你需要下载Oracle和MySQL数据库模块. DB-API 是一个规范. 它定义了一系列必须的对象和数据库存取方式, 以便为各种各样的底层数据库系统和

  • 浅谈mysql数据库中的换行符与textarea中的换行符

    1. mysql数据库中的换行符 在mysql数据库中, 其换行符为\n 即 char(10), 在python中为chr(10) 2. textarea中的换行符 textarea中的换行符为\r\n 3. web应用中换行符转换 以下是python django web的处理: # data为textarea获取的数据, 其中包括换行符`\r\n`, 以下是过渡处理 data = data.replace('\r\n', '\n') # 或 data = data.replace('\r\n

  • python使用mysql数据库示例代码

    一,安装mysql 如果是windows 用户,mysql 的安装非常简单,直接下载安装文件,双击安装文件一步一步进行操作即可. Linux 下的安装可能会更加简单,除了下载安装包进行安装外,一般的linux 仓库中都会有mysql ,我们只需要通过一个命令就可以下载安装: Ubuntu\deepin >>sudo apt-get install mysql-server >>Sudo apt-get install mysql-client centOS/redhat >&

  • Python实现mysql数据库更新表数据接口的功能

    前言 昨天,因为项目需求要添加表的更新接口,来存储预测模型训练的数据,所以自己写了一段代码实现了该功能,在开始之前,给大家分享python 操作mysql数据库基础: #coding=utf-8 import MySQLdb conn= MySQLdb.connect( host='localhost', port = 3306, user='root', passwd='123456', db ='test', ) cur = conn.cursor() #创建数据表 #cur.execute

随机推荐