# python建立题库随机抽题,用Python读取Excel题库随机组成Word版本试卷

Excel题目类型有单选、多选、判断，其中多选题最多包含6个选项，判断题只有两个选项(A：正确，B：错误)

Excel题库如图所示：

Python代码如下

import xlrd

from docx import Document

from docx.shared import Pt

from docx.oxml.ns import qn

import random

import time

def findclass(item):

single,multi,judge = 0,0,0

for i in item:

if i == "单选":

single = single + 1

elif i == "多选":

multi = multi + 1

elif i == "判断":

judge = judge + 1

return [single,multi,judge]

def joinlist(item):

item[0] = str(item[0]).replace("\n","") + "\n"

item[1] = "A." + str(item[1]).replace("\n","")

item[2] = " B." + str(item[2]).replace("\n","")

item[3] = (" C." + str(item[3]).replace("\n","") if item[3] else "")

item[4] = (" D." + str(item[4]).replace("\n","") if item[4] else "")

item[5] = (" E." + str(item[5]).replace("\n","") if item[5] else "")

item[6] = (" F." + str(item[6]).replace("\n","") if item[6] else "")

if len(item) == 8:

item[7] = " 答案：" + str(item[7]).replace("\n","") + "\n"

return ''.join(item)

else:

return ''.join(item)+ "\n"

def generate(s,a=9):

sum = ["安规周周考\n一、单选题\n"]

for i in range(len(s)):

if i < 20:

sum.append("(" + str(i+1) + ")" + joinlist(table.row_values(s[i], start_colx=1, end_colx=a)))

elif i == 20:

sum.append("二、多选题\n")

sum.append("(" + str(i+1) + ")" + joinlist(table.row_values(s[i], start_colx=1, end_colx=a)))

elif i > 20 and i < 30:

sum.append("(" + str(i+1) + ")" + joinlist(table.row_values(s[i], start_colx=1, end_colx=a)))

elif i == 30:

sum.append("三、判断题\n")

sum.append("(" + str(i+1) + ")" + joinlist(table.row_values(s[i], start_colx=1, end_colx=a)))

else:

sum.append("(" + str(i+1) + ")" + joinlist(table.row_values(s[i], start_colx=1, end_colx=a)))

return sum

def word(item,timenow,kaoshi):

doc1 = Document()

doc1.styles['Normal'].font.name = u'宋体'

doc1.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')

doc1.styles['Normal'].font.size = Pt(9)

doc1.save(kaoshi + timenow + ".docx")

data = xlrd.open_workbook("question.xlsx")

table = data.sheets()[0]

timenow = time.strftime("%Y%m%d%H%M%S", time.localtime())

a = findclass(table.col_values(0, start_rowx=0, end_rowx=None))

s = sorted(random.sample(range(1,a[0]+1),20))

m = sorted(random.sample(range(a[0]+1,a[0]+a[1]+1),10))

j = sorted(random.sample(range(a[0]+a[1]+1,a[0]+a[1]+a[2]+1),20))

s.extend(m)

s.extend(j)

word(generate(s),timenow,"kaoshidaan")

word(generate(s,8),timenow,"kaoshi")

• 2
点赞
• 15
收藏
• 0
评论
11-18 1430
10-15 1991
06-01 5500
07-08 1万+
11-04 908

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助