python 自动化办公 随机生成题库文档

HI,大家好,我是最渣的黑客,很久没有更新文章了,今天更新一篇,利用python 做一个随机生成的题库文档。对一些老师考试检测等等,可能会是一个很好的帮助。

首先要准备的是很多题库在一个EXCEL 表中,题目为第一列,答案在第二列。

如下:

 接下来是代码阶段。我这里是开发的窗口化程序。简单易懂。复制即可使用。

开发环境:

解释器:python 3.6.8

编辑器:pycharm 2019.1.3

编码格式:utf-8

需要安装的库:python-docx,pandas,xlrd 【1.2.0版本】,xlwt,

温馨提示:如果你运行出来各种报错,唯一要检查的是你的一些格式问题,库安装,环境问题。 

#encoding:utf-8
import pandas as pd
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
import random
import os
from docx.shared import Pt,RGBColor
import tkinter as tk
from tkinter import filedialog
import threading


window = tk.Tk()

window.title('随机生成题库器')
window.geometry("400x540")  # 窗口大小(长*宽)

label = tk.Label(window,text='题库数量',		#text为显示的文本内容
                 bg='black',fg='white',justify='left')         #bg为背景色,fg为前景色
label.pack(padx=50,pady=2)


textExample = tk.Text(window, width=20, height=2)  # 文本输入框
textExample.pack(padx=50,pady=10)  # 把Text放在window上面,显示Text这个控件
# textExample.insert("insert","请输入需要多少题为一个文件库")

label = tk.Label(window,text="题库文档数量",		#text为显示的文本内容
                 bg='black',fg='white',justify='left')         #bg为背景色,fg为前景色
label.pack(padx=50,pady=2)

textExample2 = tk.Text(window, width=20, height=2)  # 文本输入框
textExample2.pack(padx=50,pady=10)  # 把Text放在window上面,显示Text这个控件

label = tk.Label(window,text="文档名称",		#text为显示的文本内容
                 bg='black',fg='white',justify='left')         #bg为背景色,fg为前景色
label.pack(padx=50,pady=2)

textExample3 = tk.Text(window, width=20, height=2)  # 文本输入框
textExample3.pack(padx=50,pady=10)  # 把Text放在window上面,显示Text这个控件



def readfile(filepath):
    """
    读取EXCEL文件
    """
    datalist = []
    for d in filepath:
        data = pd.read_excel(d)
        data = data.values.tolist()

        for d in data:
            title = d[0]
            content = d[1]
            tc = [title, content]
            datalist.append(tc)

    return datalist


def wordDoc(readfile,filename,filpaths,generateNumber):
    """
    写入word文档
    filename: 文件名称
    generateNumber:随机生成多少题

    """
    data = readfile
    dataramdom = random.sample(data,int(generateNumber))
    doctitle = filename
    doc = Document()
    doc.styles['Normal'].font.name = u'宋体'
    doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    # doc.styles['Normal'].font.color.rgb = RGBColor(0, 0, 0)
    #输入文档标题
    t = doc.add_paragraph()
    t1 = t.add_run(doctitle)  # 文档总标题
    t1.font.size = Pt(15)
    t.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    t1.font.color.rgb = RGBColor(255, 0, 0)



    #输入文档内容
    for dr in dataramdom:

        title = dr[0]
        content = dr[1]
        content = str(content).replace('\n','',1)
        t2 = doc.add_paragraph().add_run(title) #输入标题
        t2.font.color.rgb = RGBColor(0, 0, 255)
        t2.bold = True
        doc.add_paragraph(content) #输入内容

    doc.save(f'{filpaths}.docx')


def makefolder(filepath):
    """
    创建文件夹
    """

    while True:
        if os.path.isdir(filepath):
            break
        else:
            os.makedirs(filepath)



def upload_file():
    """
    获取文件地址
    """
    selectFile = tk.filedialog.askopenfilenames()  # askopenfilename 1次上传1个;askopenfilenames1次上传多个
    selectFile = list(selectFile)
    upload_entry.insert(0, selectFile)
    return selectFile


def getTextInput():
    """
    获取输入
    """
    global textExample3
    countdoc1 = textExample.get("1.0", "end")  # 获取多少题
    countdoc2 = textExample2.get("1.0", "end") # 形成多少题库文档
    countdoc3 = textExample3.get("1.0", "end")
    countdoc1 = str(countdoc1).replace('\n','')
    countdoc2 = str(countdoc2).replace('\n','')
    countdoc3 = str(countdoc3).replace('\n','')

    filelist = upload_file()
    r = readfile(filelist)
    folderpath = './生成的题库'

    docName = countdoc3
    folderpath = os.path.join(folderpath, docName)
    makefolder(folderpath)  # 创建文件夹
    n = int(countdoc2)
    m = 0
    while True:
        m += 1
        if m > n:
            break
        else:
            filename = docName + "_" + str(m)
            filapathName = os.path.join(folderpath, filename)
            print(f"{filename} 生成成功")
            wordDoc(r,countdoc3,filapathName,countdoc1)

def thread_it(func):
    '''将函数打包进线程'''
    # 创建
    t = threading.Thread(target=func)
    # 守护 !!!
    t.setDaemon(True)
    # 启动
    t.start()
    # 阻塞--卡死界面!

#输入文件
upload = tk.Frame(window)
upload.pack(padx=20,pady=20)
upload_entry = tk.Entry(upload, width='40')
upload_entry.pack(padx=50,pady=10)

import time
nowtime = time.time()

nowtime1 = int(time.time())
nowtime2 = int(time.time())+3000


btnRead = tk.Button(window, height=1, width=10, text="开始程序", command=lambda:thread_it(getTextInput))
btnRead.pack(padx=50,pady=10)  # 显示按钮


window.mainloop()

软件最终呈现如下:

题库数量表示:一个文档有多少个题

题库文档数量表示:你需要生成多个文档

文档名称:文档的主要内容的主标题,也是文档的文件名称

 

如果这篇文章对你有帮助,记得点个关注!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宋哈哈呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值