父爱如山 - 为了闺女数学口算

119 阅读1分钟

为了闺女,我写自动生成题目并生成word方便打印。


# -*- coding: utf-8 -*-

import random
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

from docx.table import _Cell
from docx.oxml import OxmlElement
from docx.oxml.ns import qn


def set_cell_border(cell: _Cell, **kwargs):
    """
    Set cell`s border
    Usage:
    set_cell_border(
        cell,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        start={"sz": 24, "val": "dashed", "shadow": "true"},
        end={"sz": 12, "val": "dashed"},
    )
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
 
    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)
 
    # list over all available tags
    for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)
            # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)
            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))

def create_questions(num_questions):
    questions = []
    for _ in range(num_questions):
        num1 = random.randint(0, 20)
        num2 = random.randint(0, 20)
        operator = random.choice(['+', '-'])
        # Ensure result is not negative
        if operator == '-' and num2 > num1:
            num1, num2 = num2, num1
        questions.append(f'{num1} {operator} {num2} =   ')
    return questions

def write_questions_to_docx(questions, questions_per_row, filename='questions.docx'):
    doc = Document()

    # Add title
    title = doc.add_paragraph()
    title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    run = title.add_run("父爱如山")
    run.font.size = Pt(16)

    # Add questions
    for i in range(0, len(questions), questions_per_row):
        row_questions = questions[i:i+questions_per_row]
        table = doc.add_table(rows=1, cols=len(row_questions))
        for idx, cell in enumerate(table.rows[0].cells):
            set_cell_border(cell, 
                            top={"sz": 12, "val": "dashed", "color": "#FFFFFF"},
                            bottom={"sz": 12,  "val": "dashed", "color": "#FFFFFF"},
                            start={"sz": 12, "val": "dashed", "color": "#FFFFFF"},
                            end={"sz": 12, "val": "dashed", "color": "#FFFFFF"}
                        )
            cell.text = row_questions[idx]
            cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    
    doc.save(filename)


if __name__ == "__main__":
    questions = create_questions(3000)
    write_questions_to_docx(questions, 5, "父爱如山.docx")