自动生成一个10页的19行x3列的小学数学计算题,包括加减乘除运算,
可以给家里的娃训练数学运算能力。
命令行运行程序,直接生成excel文件,打开即可以打印。
#! /usr/bin/env python3
import xlsxwriter
import math
import random
align_right_format = None
normal_format = None
line_format = None
normal_format2 = None
line_format2 = None
def write_str(ws, row, col, row_len, str, format, format2):
slen = len(str)
x = col + row_len - slen
for c in str:
if c >= '0' and c <= '9' :
ws.write_number(row, x, int(c), format)
elif c == 'A':
ws.write(row,x, " ", format2)
elif c == '=':
ws.write_string(row,x, "=", format2)
else:
ws.write_string(row, x, c, format)
x = x + 1
def add_formula(ws, x, y, op, col_x, row_y, end):
ops = ['+', '-', '×', '÷']
if x < y and (op == 1 or op == 3) :
(x,y) = (y,x)
x_s = "%d" % x
y_s = "%d" % y
write_str(ws, row_y, col_x, 2, x_s, normal_format, normal_format)
col_x = col_x + 2
write_str(ws, row_y, col_x, 1, ops[op], normal_format, normal_format)
col_x = col_x + 1
write_str(ws, row_y, col_x, 2, y_s, normal_format, normal_format)
col_x = col_x + 2
write_str(ws, row_y, col_x, 1, "=", normal_format, normal_format)
col_x = col_x + 1
if end:
write_str(ws, row_y, col_x, 4, " ", normal_format, normal_format)
def gen2_2(ws):
for x in range(0, 35):
ws.set_row(x, 20)
for x in range(0, 35):
ws.set_column(x, x, 0.8, normal_format)
for row in range(0, 19):
for col in range(0, 3):
row_y = row * 2
col_x = col * 11
op = random.randint(0,3)
if op == 3:
x = random.randint(2,50)
y = random.randint(2,30)
x = x * y
else :
x = random.randint(2,20)
y = random.randint(5,30)
if col == 2 :
add_formula(ws, x, y, op, col_x, row_y, True)
else :
add_formula(ws, x, y, op, col_x, row_y, False)
if __name__ == "__main__" :
wb = xlsxwriter.Workbook("m2.xlsx")
for i in range(1,11):
ws = wb.add_worksheet("一百以内加减乘除%2d" % i)
align_right_format = wb.add_format({'align': "right"})
normal_format = wb.add_format({
'align': 'center', # 水平居中
'border' : 4,
'valign': 'vcenter', # 垂直居中
'bold': True, # 加粗(默认False)
'font': u'Consolas', # 字体
'font_size': 11,
'fg_color': '#FFFFFF', # 背景色
'color': 'black' # 字体颜色
})
gen2_2(ws)
wb.close()