一、背景
本文章主要是分享如何使用Python从MySQL数据库中面抽取试题,生成的试卷每一份都不一样。
二、准备工作
1.安装Python3
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.st