python生成随机的测验试卷_Python+MySQL随机试卷及答案生成程序的示例代码

一、背景

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

二、准备工作

1.安装Python3

2.安装库

pip installpython-docx==0.8.10

pip installPyMySQL==1.0.2

3.试题库.xlsx

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

选择题数据库截图:

53dd50c430c20ae7581b35c5951957c6.png

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

ac073fe50a24bcece3e83462ba05e521.png

三、代码

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.st

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值