小学生的计算题自动生成小程序「python」
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#liuqiping fred
from docx import Document
from docx.shared import Inches
import random
#参数说明:mathnumber:生成的题目数量
#mathmathod:生成的题目数量
#mathlevel=1:题目难度
# 1表示1-10以内的算式,2表示11-20以内的算式...10表示91-100以内的算式
#方法说明:用于生成小学生数学题目并输出到word文档上,供小朋友进行练习
def buildmath(mathnumber = 100, mathmathod=1, mathlevel=1, mathleveltype = 1):
multimath = []
mathlevelconfig_1 = [[1,10],[11,20],[21,30],[31,40],[41,50],[51,60],[61,70],[71,80],[81,90],[91,100] ]
mathlevelconfig_2 = [[1,10],[1,20],[11,30],[21,40],[21,50],[31,60],[31,70],[41,80],[41,90],[51,100] ]
if mathleveltype == 1:
mathlevelconfig = mathlevelconfig_1
elif mathleveltype == 2:
mathlevelconfig = mathlevelconfig_2
mathlevel = mathlevel - 1 #将难度等级映射到列表下标上
for i in range(mathnumber):
a = random.randint(mathlevelconfig[mathlevel][0], mathlevelconfig[mathlevel][1] )
b = random.randint(mathlevelconfig[mathlevel][0], mathlevelconfig[mathlevel][1] )
if mathmathod == 1:
c = a + b
elif mathmathod == 2:
c = a * b
print('等式为: %d + %d = %d \n' %(a, b , c))
singlemath = buildsinglemath(a, b, c, mathmathod)
singlemath = singlemath.ljust(50) #补充到30的长度
multimath.append(singlemath)
print(multimath)
return multimath
def buildsinglemath(a, b, c,mathmathod):
blankstr = r'( )'
blank = random.randint(1,3)
a = str(a)
b = str(b)
c = str(c)
singlemath = ''
if blank == 1 :
a = blankstr
elif blank == 2 :
b = blankstr
else :
c = blankstr
if mathmathod == 1:
singlemath = a + r' + ' + b + r' = ' + c
elif mathmathod == 2:
singlemath = a + r' x ' + b + r' = ' + c
print(singlemath)
return singlemath
def mathtodocx(multimath, docfile=r'/home/liuqp1/Documents/pywork/shuxuexiti/demo.docx'):
document = Document()
document.add_heading('小学生数学计算练习题')
rowmath = ''
rownum = 0
for item in multimath:
rownum = rownum + 1
rowmath = item + rowmath
#每3题输出到一行
if rownum % 3 == 0 :
#p = document.add_paragraph(item)
p = document.add_paragraph('')
p.add_run(rowmath).bold = True
rowmath =''
#最后一行补充输出到文档上
if rownum % 3 > 0 :
p = document.add_paragraph('')
p.add_run(rowmath).bold = True
document.save(r'/home/liuqp1/Documents/pywork/shuxuexiti/demo.docx')
if __name__ == '__main__':
#参数说明:mathnumber:生成的题目数量
#mathmathod:生成的题目数量
#mathlevel=1:题目难度
# 1表示1-10以内的算式,2表示11-20以内的算式...10表示91-100以内的算式
#方法说明:用于生成小学生数学题目并输出到word文档上,供小朋友进行练习
multimath = buildmath(mathnumber = 804, mathmathod=2, mathlevel=1, mathleveltype = 1)
mathtodocx(multimath)
print('完成计算题的生成')