python 生成小学计算练习 docx

python3 生成二年级下计算练习,有口算,有竖式。

 

import random
import osfrom docx.shared import Pt
from docx import Document

def create_page(document):
    #口算
    document.add_paragraph('一、口算')
    operators='+-×÷'
    columnsNumber = 3
    rowsNumbers = 8
    table = document.add_table(rows=rowsNumbers, cols=columnsNumber)
    for row in range(rowsNumbers):
        for col in range(columnsNumber):
            operator = random.choice(operators)
            first = random.randint(11, 100)
            second = random.randint(11, 100)
            if operator == '×' or operator == '÷':
                first = random.randint(2, 9)
                second = random.randint(2, 9)
            
            if operator == '÷':
                first=first*second
                                
            if operator == '-' or  operator == '+':
                if first < second:
                    first, second = second, first
                if second < 30:
                    first*=10
                    second*=10
                if second < 20:
                    first*=10
                    second*=10
            
            if operator == '+':
                first=first-second
            
            r = str(first) + ' ' + operator +' '+ str(second) + '='
            cell = table.cell(row, col)
            cell.text = r
            
    #竖式
    document.add_paragraph('')
    document.add_paragraph('二、竖式')
    operators='+-÷'
    columnsNumber = 5
    rowsNumbers = 7
    table = document.add_table(rows=rowsNumbers, cols=columnsNumber)
    for row in range(int(rowsNumbers/4)+1):
        for col in range(int(columnsNumber/2)+1):
            operator = random.choice(operators)
            first = random.randint(100, 1000)
            second = random.randint(100, 1000)
            if operator == '÷':
                first = random.randint(2, 9)
                second = random.randint(2, 9)
                residue = random.randint(1, second-1)
                first=first*second+residue
                                
            if operator == '-' or  operator == '+':
                if first < second:
                    first, second = second, first
            
            if operator == '+':
                first=first-second
                        
            r = str(first) + ' ' + operator +' '+ str(second) + '='
            cell = table.cell(row*4, col*2)
            cell.text = r
    

def create_docx():
    document = Document()
    document.styles['Normal'].font.name = '微软雅黑'
    document.styles['Normal'].font.size = Pt(12)
    
    pageSize=10 # 页数
    for i in range(0,pageSize):
        if i!=0:
            document.add_page_break()
        create_page(document)
        
    document.save('二年级下计算练习.docx')
    os.startfile("二年级下计算练习.docx")

if __name__ == '__main__':
    create_docx()

 

posted @ 2023-06-21 09:17  上位机  阅读(134)  评论(0编辑  收藏  举报