当前位置: 首页 > news >正文

【教学类-52-11】20240919动物数独(4宫格)1图、2图、6图、有答案、无答案 组合版18套

一、背景需求

昨天修改了四宫格数独的代码,把任务卡从一页6张改成一页2张

【教学类-52-10】20240919动物数独(4宫格)一页2张任务卡,有答案,最大图卡(最适合的商品)-CSDN博客文章浏览阅读553次,点赞12次,收藏6次。【教学类-52-10】20240919动物数独(4宫格)一页2张任务卡,有答案,最大图卡(最适合的商品)https://blog.csdn.net/reasonsummer/article/details/142387324

同时在小红书里更改了商品图片

然后我想到一个问题:万一有客户对任务卡的大小(1页1图、1页2图、1页6图)或操作卡(1页1图、1页2图,1页6图)有不同的组合需求,那么我还要重新跑代码生成组合样式。

可是随机数独部分的代码生成时间实在太长了40分钟,跑一次太耗时。我想能不能直接做一套代码,自动生成所有可能生产的组合样式?

二、解题思路:

目前根据A4纸大小,共设计了三种图示大小

也就是说,在A4纸基础上,数独任务卡、动物操作卡、答案卡有三种样式:

1图19.6*19.6CM 

2图14.1*14.1CM 

6图9.39*9.39CM 

各种大小的卡片的组合方式如下:

1、无答案组合(9种)

动物操作卡1图+任务卡1图

动物操作卡1图+任务卡2图

动物操作卡1图+任务卡6图

动物操作卡2图+任务卡1图

动物操作卡2图+任务卡2图

动物操作卡2图+任务卡6图

动物操作卡6图+任务卡1图

动物操作卡6图+任务卡2图

动物操作卡6图+任务卡6图

 2、有答案组合27种(只要其中9种,任务卡和答案卡一样大,便于正反黏贴)

动物操作卡1图+任务卡1图+答案卡1图

动物操作卡1图+任务卡2图+答案卡2图

动物操作卡1图+任务卡6图+答案卡6图

动物操作卡2图+任务卡1图+答案卡1图

动物操作卡2图+任务卡2图+答案卡2图

动物操作卡2图+任务卡6图+答案卡6图

动物操作卡6图+任务卡1图+答案卡1图

动物操作卡6图+任务卡2图+答案卡2图

动物操作卡6图+任务卡6图+答案卡6图

三、设计结果

2024年9月22日,经过一整天的代码调式,终于把整个环节打通了。


# -*- coding:utf-8 -*-'''
制作动物/脸谱数独4宫格的黏贴关卡 A4 1图2图6图的所有组合 
1.无答案:9种3:3,两两组合
2.有答案:27种 3:3:3,三三组合(实际需要其中9种)
作者:AI对话大师,阿夏
时间:2024年9月19日
'''print('-----第一板块、动物操作卡(大图片卡一页1图、1页2图 一页6图)-------')# print('----1、读取行列-------')
import os,time
from docx import Document
from docx.shared import Cm
from docx2pdf import convert
from PyPDF2 import PdfMerger
import shutilpath=r'C:\Users\jg2yXRZ\OneDrive\桌面\动物数独4宫格'psize=[19.6,14.1,9.39]
pg=[1,2,6]
gzs=[1,2,2]for pt in range(len(pg)):# # 新建一个”装N份word和PDF“的临时文件夹imagePath=path+r'\\零时Word'os.makedirs(imagePath,exist_ok=True)  # 若图片文件夹不存在就创建imagePathpaste=path+r'\\05操作卡pdf'os.makedirs(imagePathpaste,exist_ok=True) doc = Document(path +fr'\动物数独(4宫格横板){pg[pt]}图关卡.docx')# 获取文档中的所有表格tables = doc.tables# 选择你需要读取的表格(在这种情况下是第1张表格)target_table = tables[0]# 获取所选表格的行数和列数num_rows = len(target_table.rows)num_columns = len(target_table.columns)print("行数:", num_rows)# 3print("列数:", num_columns)# # 2 print('----2、读取图片-------')import os# 指定文件夹路径folder_path = path + r'\02动物图片'pic_list = [os.path.join(folder_path, file_name) for file_name in os.listdir(folder_path)]*4# print(pic_list)# print(len(pic_list))groups = [pic_list[i:i + int(pg[pt])] for i in range(0, len(pic_list), int(pg[pt]))]print(groups)print(len(groups))# # # print('----3、黏贴图片卡,一页1图、1页2图 一页6图-------')# 处理每一组图片for group_index, group in enumerate(groups):# 创建新的Word文档doc = Document(path + fr'\动物数独(4宫格横板){pg[pt]}图关卡.docx')# print(group)# 遍历每个单元格,并插入图片for cell_index, image_file in enumerate(group):# 计算图片长宽(单位:厘米)cc=float(psize[pt])# 插入图片到单元格table = doc.tables[0]cell = table.cell(int(cell_index / int(gzs[pt])), cell_index % int(gzs[pt]))#         # 如果第一行有4个格子,两个数字都写4cell_paragraph = cell.paragraphs[0]cell_paragraph.clear()run = cell_paragraph.add_run()run.add_picture(os.path.join(image_file), width=Cm(cc), height=Cm(cc))cell_paragraph.alignment = 1  # 设置单元格中的文本居中# 保存修改后的.docx文件doc.save(imagePath + fr'\{group_index + 1:02d}页.docx')# docx 文件另存为PDF文件inputFile = imagePath + fr'\{group_index + 1:02d}页.docx'  # 要转换的文件:已存在outputFile = imagePath + fr'\{group_index + 1:02d}页.pdf'  # 要生成的文件:不存在convert(inputFile, outputFile)time.sleep(8)# 合并PDF文件pdf_lst = [f for f in os.listdir(imagePath) if f.endswith('.pdf')]pdf_lst = [os.path.join(imagePath, filename) for filename in pdf_lst]pdf_lst.sort()file_merger = PdfMerger()for pdf in pdf_lst:file_merger.append(pdf)file_merger.write(imagePathpaste + fr"\03 {pg[pt]:02}图操作卡.pdf")file_merger.close()# 删除零时文件夹shutil.rmtree(imagePath)print('-----第二板块、动物任务卡和答案卡一套,只要JPG-------')import random
from win32com.client import constants, gencache
from win32com.client.gencache import EnsureDispatch
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPHimport docxtpl
import pandas as pd
from docx2pdf import convertfrom docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
import copynum=1
# int(input('生成几份\n'))
# 制作"单元格"# 几宫格
hsall=4
# int(input('请输入4或9\n'))
hs=hsall# kk=int(input('空格数量,输入5,就是50%,就是空一半)\n'))print('------3-1、如果正好想生成1空、2空、3空、4空的数字,需要测算百分比的具体数字------')n=hsall
g=n*na=[]
for i in range(1,101):# 因为有100,所以三位数print(f'{n}宫格,难度{i:03d},抽取{i:03d}%:实际有{int(g*i/100):03d}空,已有图案{g-int(g*i/100):03d}')a.append(f'{n}宫格,难度{i:03d},抽取{i:03d}%:实际有{int(g*i/100):03d}空,已有图案{g-int(g*i/100):03d}')
print(a)
print(len(a))
# # 用冒号分割,如果0空,加入,# 创建一个空列表用于存储匹配的元素
b = []# 遍历原始列表
for element in a:# 如果找到匹配的元素,以":"为分隔符将字符串分割成两部分parts = element.split(":")# print(parts)# # 提取第一部分中包含的数字信息info = parts[1]b.append(info)
# 对列表b进行排序,并去除重复项
b = list(set(b))
b.sort(reverse=False)
print(b)f=[]
for d in range(len(b)):for c in a:# print(c)# 读取一个就中断if c[-15:]==b[d]:f.append(c)break
f.pop(0)
# 删除['4宫格,难度01,抽取1%:实际有00空,已有图案14', 
# f.pop(-1)
# # 删除'4宫格,难度100,抽取100%:实际有14空,已有图案00'
print(f)
# ['4宫格,难度007,抽取007%:实际有001空,已有图案015', '4宫格,难度013,抽取013%:实际有002空,已有图案014', '4宫格,难度019,抽取019%:实际有003空,已有图案013', '4宫格,难度025,抽取025%:实际有004空
# ,已有图案012', '4宫格,难度032,抽取032%:实际有005空,已有图案011', '4宫格,难度038,抽取038%:实际有004空,已有图案010', '4宫格,难度044,抽取044%:实际有007空,已有图案009', '4宫格,难度050,抽取050%:实际有008空,已有图案008', '4宫格,难度057,抽取057%:实际有009空,已有图案007', '4宫格,难度043,抽取043%:实际有010空,已有图案004', '4宫格,难度049,抽取049%:实际有011空,已有图案005', '4宫格,
# 难度075,抽取075%:实际有012空,已有图案004', '4宫格,难度082,抽取082%:实际有013空,已有图案003', '4宫格,难度088,抽取088%:实际有014空,已有图案002', '4宫格,难度094,抽取094%:实际有015空,已有图案
# 001']
print(len(f))
# 15
# 难度有15关# 提取百分数
g=[]
w=[]
for p in f:g.append(int(p[12:15]))    # 提取第4-7个数字=百分比数字w.append(int(p[20:23]))    # 提取空格数量
print(g)
# [7, 13, 19, 25, 32, 38, 44, 50, 57, 43, 49, 75, 82, 88, 94]
print(len(g))
# 15关
print(w)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print(len(w))
# 34print('------2、制作4宫格随机数字------')# 制作"单元格"# 几宫格
for kk in range(len(g)):
# hs=int(input('请输入宫格数量(3,5.4,7,8,)\n'))# 因为有3-9的不同word模板,所以有不同的套数和字体大小ll=['4'] # 如果输入345mm=['11']# 3对应的套数是4*3套nn=['34']# 3对应的写入单元格的数字大小34磅 for r in range(len(ll)):if hs ==int(ll[r]):# 底边几套.底边看有2份db=int(mm[r][0])# int(input('底边几套? 3\n'))# 侧边几套 侧边看也是2份print(db )        cb=int(mm[r][1])# int(input('侧边几套? 2\n'))print(cb)size=int(nn[r])print(size)        # 写入单元格数字的大小(撑满格子)path=r'C:\Users\jg2yXRZ\OneDrive\桌面\动物数独4宫格'# 新建一个”装N份word和PDF“的临时文件夹imagePath=path+r'\\零时Word'os.makedirs(imagePath,exist_ok=True) imagePatha=path+r'\06答案卡'imagePathq=path+r'\07任务卡'os.makedirs(imagePatha,exist_ok=True)os.makedirs(imagePathq,exist_ok=True)# 计算不同模板中的单元格坐标,放在bg里# 棋盘格子数量,# 如果长方形:底边3*侧边2,3*2=4套 ,就是10*10宫格,底边格子数量就是10*3=30,侧边格子数量就是10*2=20,# if db==cb:db_size = hs*dbcb_size=  hs*cbprint('{}宫格排列底{}侧{}共{}套,底边格子数{}'.format(hs,db,cb,db*cb,db_size ))print('{}宫格排列底{}侧{}共{}套,侧边格子数{}'.format(hs,db,cb,db*cb,cb_size ))# 确定每个宫格的左上角坐标 00 04 40  44 中间没有分栏的空格了,所以hs不用+1bgszm=[]for a in range(0,cb_size,hs):    # 0-11每隔4,写一个坐标  侧边yfor b in range(0,db_size,hs):  # 0-11每隔4,写一个坐标  侧边xbgszm.append('{}{}'.format('%02d'%a,'%02d'%b))print(bgszm)# 10宫格排列底3侧2共4套,底边格子数30# 10宫格排列底3侧2共4套,侧边格子数20# 10宫格排列底3侧2共4套,侧边格子数20# ['0000', '0010', '0020', '1000', '1010', '1020']# 转为元祖start_coordinates = [(int(s[0:2]), int(s[2:4])) for s in bgszm]cell_coordinates = []# 推算每个起始格子后面的单元格数字for start_coord in start_coordinates:i, j = start_coordsubgrid_coordinates = []for x in range(hs):for y in range(hs):subgrid_coordinates.append((i + x, j + y))cell_coordinates.append(subgrid_coordinates)# 打印结果(元祖样式)bg=[]for coordinates in cell_coordinates:# print(coordinates)     # [(4, 8), (4, 9), (4, 10), (5, 8), (5, 9), (5, 10), (4, 8), (4, 9), (4, 10)]for c in  coordinates:print(c)        # 元组 (1, 2) 样式s = ''.join(str(num).zfill(2) for num in c)   # zfill将元组 (1, 2) 转换为字符串 '0102' 特别是(5,10)这种必须转成2个数字0510print(str(s))        #  '12'bg.append(s)  #  '0102'print(bg)# 生成PDfP=[] for z in range(num):  P.clear()#    制作4份数据for j in range(db*cb):    #  3宫格,4*3=12套def generate_sudoku_board():# 创建一个9x9的二维列表,表示数独棋盘board = [[0] * hs for _ in range(hs)]# 递归函数,用于填充数独棋盘的每个单元格def filling_board(row, col):# 检查是否填充完成整个数独棋盘if row == hs:return True# 计算下一个单元格的行和列索引next_row = row if col < hs-1 else row + 1next_col = (col + 1) % hsimport mathr = int(math.sqrt(hs))print(r)# 获取当前单元格在小九宫格中的索引box_row = row // rbox_col = col // r# 随机生成1到9的数字numbers = random.sample(range(1, hs+1), hs)for num in numbers:# 检查行、列、小九宫格是否已经存在相同的数字if num not in board[row] and all(board[i][col] != num for i in range(hs)) and all(num != board[i][j] for i in range(box_row*r, box_row*r+r) for j in range(box_col*r, box_col*r+r)):board[row][col] = num# 递归填充下一个单元格if filling_board(next_row, next_col):return True# 回溯,将当前单元格重置为0board[row][col] = 0return False# 填充数独棋盘filling_board(0, 0)return board# 第一种是出现全部数字,也就是出现全部图案board1 = generate_sudoku_board()# 定义类型1def create_board1():                return board1# 定义类型2def create_board2(): # level数字越大代表游戏难度越大"""生成一个随机的数独棋盘,空白格少"""global board1  # 全局变量# 第二种定量出现空白格子board2 =  copy.deepcopy(board1)ggg=int(g[kk])blanks = random.sample(range(hs*hs), int(float(hs*hs*ggg)/100))  # 16*97/100=15.52是浮点数,然后再转成整数# blanks = 0for i in blanks:row = i // hscol = i % hsboard2[row][col] = 0# if random.randint(0, hs) < level:#     board1[row][col] = 0return board2# 16个数字v1 = create_board1()    # 16-X个数字    v2 = create_board2()v=v1+v2print(v)# [[1, 4, 2, 3], [3, 2, 4, 1], [4, 1, 3, 2], [2, 3, 1, 4], [1, 4, 2, 3], [3, 2, 4, 1], [4, 1, 3, 2], [0, 3, 1, 4]]# 提取每个数字P = ['' if a2 == 0 else a2 for a1 in v for a2 in a1]print(P)print(len(P))# [1, 4, 2, 3, 3, 2, 4, 1, 4, 1, 3, 2, 2, 3, 1, 4, 1, 4, 2, 3, 3, 2, 4, 1, 4, 1, 3, 2, '', 3, 1, 4]half_len = int(len(P) // 2)Q = [P[i:i+half_len] for i in range(0, len(P), half_len)]print(Q)# [[1, 4, 2, 3, 3, 2, 4, 1, 4, 1, 3, 2, 2, 3, 1, ],[4, 1, 4, 2, 3, 3, 2, 4, 1, 4, 1, 3, 2, '', 3, 1, 4]]time.sleep(10)          print('------答案卡和题目卡------')  title=['答案卡','任务卡']imagePath1=path+r'\答案卡1'imagePath2=path+r'\任务卡1'os.makedirs(imagePath1,exist_ok=True)os.makedirs(imagePath2,exist_ok=True)ti=[path+r'\答案卡1',path+r'\任务卡1']       for tt in range(len(Q)):          doc = Document(path+r'\动物数独(4宫格横板).docx')  # 获取第一个表格,写难度用的table = doc.tables[0]for b1 in range(0,1):# 在'00'单元格中插入文本cell_00 = table.cell(0, b1)cell_00_paragraph = cell_00.paragraphs[0]cell_00_paragraph.text =f"第 {kk+1} 关 {title[tt]}"cell_00_paragraph.style.font.bold = Truecell_00_paragraph.style.font.size = Pt(24)cell_00_paragraph.style.font.name = "黑体"cell_00_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER#    table = doc.tables[1]          # 表0,表2 写标题用的# 标题写入3、5单元格  for t in range(0,len(bg)):             # 0-5是最下面一行,用来写关卡数字pp=int(bg[t][0:2])     # qq=int(bg[t][2:4])k=str(Q[tt][t])              # 提取list图案列表里面每个图形  t=索引数字print(pp,qq,k)# 图案符号的字体、大小参数run=table.cell(pp,qq).paragraphs[0].add_run(k)    # 在单元格0,0(第1行第1列)输入第0个图图案run.font.name = '黑体'#输入时默认华文彩云字体# run.font.size = Pt(44)  #输入字体大小默认30号 换行(一页一份大卡片run.font.size = Pt(size) #是否加粗# run.font.color.rgb = RGBColor(150,150,150) #数字小,颜色深0-255run.font.color.rgb = RGBColor(0,0,0) #数字小,颜色深0-255run.bold=True# paragraph.paragraph_format.line_spacing = Pt(180) #数字段间距r = run._elementr.rPr.rFonts.set(qn('w:eastAsia'), '黑体')#将输入语句中的中文部分字体变为华文行楷table.cell(pp,qq).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER#居中  doc.save(ti[tt]+fr'\{z+1:02d}.docx')time.sleep(5)print('------4、每张word转为pdf----')      from docx import Documentfrom docx.shared import Cm# 读取四张卡通动物的文件名animal_path = path+r'\02动物图片'  # 替换为实际的文件夹路径# 获取文件夹中所有文件的完整路径file_paths = [os.path.join(animal_path, file_name) for file_name in os.listdir(animal_path)]print(file_paths)doc = Document(ti[tt]+fr'\{z+1:02d}.docx')# 获取所有表格tables = doc.tables# 遍历每个表格for table in tables:# 遍历表格的行for i, row in enumerate(table.rows):# 遍历行的单元格for j, cell in enumerate(row.cells):# 读取单元格的文本值cell_text = cell.textfor x in range(0,hs):# 判断单元格的值是否为1if cell_text == f'{x+1}':# 删除原来的文本cell.text = ''# 插入图片run = cell.paragraphs[0].add_run()# 4.8格子run.add_picture(file_paths[x], width=Cm(4.8), height=Cm(4.8))# 设置图片对齐方式为居中run.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER# 设置单元格的水平和垂直对齐方式为居中cell.vertical_alignment = WD_ALIGN_PARAGRAPH.CENTERcell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER# 保存修改后的文档doc.save(ti[tt]+fr'\{z+1:02d}.docx')time.sleep(5)# # 关闭Word文档# doc.close()from docx2pdf import convert# docx 文件另存为PDF文件inputFile = ti[tt]+fr'\{z+1:02d}.docx'outputFile =ti[tt]+fr'\{z+1:02d}.pdf'# 先创建 不存在的 文件f1 = open(outputFile, 'w')f1.close()# 再转换往PDF中写入内容convert(inputFile, outputFile)time.sleep(10)       print('----------更改pdf新名字------------')                    # 两个pdfimport osfrom PyPDF2 import PdfFileReader, PdfFileWritertii=[path+r'\06答案卡',path+r'\07任务卡']for t3 in range(len(tii)):pdf_lst = [f for f in os.listdir(ti[t3]) if f.endswith('.pdf')]pdf_path = os.path.join(ti[t3], pdf_lst[0]) print(pdf_path)         # 源头文件名C:\Users\jg2yXRZ\OneDrive\桌面\动物数独4宫格\答案卡1\01.pdf    new_file_name = f"{title[t3]} 动物拼图{hs}宫格 难度{kk+1:02d} 空{int(w[kk]):03d}格({db}乘{cb}等于{num}份{db*cb}张).pdf"  # 重命名并移动文件到imagePatha文件夹下output_path = os.path.join(tii[t3], new_file_name)print(output_path)# 目标文件名C:\Users\jg2yXRZ\OneDrive\桌面\动物数独4宫格\答案卡\答案卡 动物拼图4宫格 难度01 空001格(1乘1等于1份1张).pdfos.rename(pdf_path, output_path)            # 源文件名,目标文件名time.sleep(5)   shutil.rmtree(ti[t3]) #递归删除文件夹,即:删除非空文件夹time.sleep(3)    # 防止转换时报错,预留生成时间# print('----------第4步:把都有16管PDF关卡变png------------')#coding=utf-8
from win32com.client import Dispatch
import os
import re
import fitzwdFormatPDF = 17 #转换的类型
zoom_x=2 #尺寸大小,越大图片越清晰 5超大,这里改成2
zoom_y=2 #尺寸大小,越大图片越清晰,长宽保持一致
rotation_angle=0#旋转的角度,0为不旋转li=[path+r'\06答案卡',path+r'\07任务卡']
for l in li:for root, dirs, files in os.walk(l):for file in files:if re.search('\.pdf$', file):filename = os.path.abspath(root + "\\" + file)print(filename)# 打开PDF文件pdf = fitz.open(filename)# 逐页读取PDFfor pg in range(0, pdf.pageCount):page = pdf[pg]# 设置缩放和旋转系数trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle)pm = page.getPixmap(matrix=trans, alpha=True)# 开始写图像pm.writePNG(filename.replace('.pdf', '') + str(pg+1) + ".png")pdf.close()# 删除生成文件PDF  for parent, dirnames, filenames in os.walk(l):for fn in filenames:if fn.lower().endswith('.pdf'):os.remove(os.path.join(parent, fn))print('-----第三板块、把动物任务卡和答案卡一套分别做成1页1份,1页2份,1页6份的pdf-------')psize=[9.39,9.39,14.1,14.1,19.6,19.6]
# ,
pg=[6,6,2,2,1,1]
# ,'2',
gzs=[2,2,2,2,1,1]
# '1','2',
nh=[1,2,1,2,1,2]# print('----1、读取行列-------')
from docx import Document
from docx.shared import Cm
import osfor x in range(len(pg)):    # # 新建一个”装N份word和PDF“的临时文件夹    imagePath11=path+r'\08答案卡pdf'imagePath22=path+r'\09任务卡pdf'os.makedirs(imagePath11,exist_ok=True)os.makedirs(imagePath22,exist_ok=True)tiii=[path+r'\08答案卡pdf',path+r'\09任务卡pdf',path+r'\08答案卡pdf',path+r'\09任务卡pdf',path+r'\08答案卡pdf',path+r'\09任务卡pdf']tii=[path+r'\06答案卡',path+r'\07任务卡',path+r'\06答案卡',path+r'\07任务卡',path+r'\06答案卡',path+r'\07任务卡']title=['答案卡','任务卡','答案卡','任务卡','答案卡','任务卡']# for x in range(len(tiii)):imagePath=path+r'\\零时Word'os.makedirs(imagePath,exist_ok=True)  # 若图片文件夹不存在就创建# 打开.docx文件doc = Document(path +fr'\动物数独(4宫格横板){pg[x]}图关卡.docx')# 获取文档中的所有表格tables = doc.tables[0]import os           
#       file_paths = [os.path.join(tii[x], file) for file in os.listdir(tii[x])]# file_paths = [os.path.join(root, file) for root, dirs, files in os.walk(tii[x]) for file in files]      pic_list_six = [file_paths[i:i+int(pg[x])] for i in range(0, len(file_paths), int(pg[x]))]print(pic_list_six)print(len(pic_list_six))# # # print('----3、黏贴图片卡,一页1图、1页2图 一页6图-------')# 处理每一组图片for group_index, group in enumerate(pic_list_six):# 创建新的Word文档doc = Document(path + fr'\动物数独(4宫格横板){pg[x]}图关卡.docx')# print(group)# 遍历每个单元格,并插入图片for cell_index, image_file in enumerate(group):# 计算图片长宽(单位:厘米)cc=float(psize[x])# 插入图片到单元格table = doc.tables[0]cell = table.cell(int(cell_index / int(gzs[x])), cell_index % int(gzs[x]))#         # 如果第一行有4个格子,两个数字都写4cell_paragraph = cell.paragraphs[0]cell_paragraph.clear()run = cell_paragraph.add_run()run.add_picture(os.path.join(image_file), width=Cm(cc), height=Cm(cc))cell_paragraph.alignment = 1  # 设置单元格中的文本居中# 保存修改后的.docx文件doc.save(imagePath + fr'\{group_index + 1:02d}页.docx')# docx 文件另存为PDF文件inputFile = imagePath + fr'\{group_index + 1:02d}页.docx'  # 要转换的文件:已存在outputFile = imagePath + fr'\{group_index + 1:02d}页.pdf'  # 要生成的文件:不存在convert(inputFile, outputFile)time.sleep(8)pdf_lst = [f for f in os.listdir(imagePath) if f.endswith('.pdf')]pdf_lst = [os.path.join(imagePath, filename) for filename in pdf_lst]pdf_lst.sort()file_merger = PdfMerger()for pdf in pdf_lst:print(pdf)file_merger.append(pdf)# file_merger.write("C:/Users/jg2yXRZ/OneDrive/桌面/描字帖/(打印合集)大班A整页描字帖2乘5加表格-4名字-({}人).pdf".format(num))file_merger.write(tiii[x]+ fr"\{nh[x]:02} {pg[x]:02}图{title[x]}.pdf")# 01 06图答题卡.pdf# 02 06图任务卡.pdffile_merger.close()# doc.Close()# # print('----------第5步:删除临时文件夹------------')    import shutilshutil.rmtree(imagePath) #递归删除文件夹,即:删除非空文件夹# import shutil# shutil.rmtree(imagePath2) #递归删除文件夹,即:删除非空文件夹print('-----第四板块、交叉合并有答案6套,无答案6套(1-1-1、1-1,1-2-2,1-2,2-1-1,2-1……----')
# 无答案:对09、05、文件夹(每份3个文件),进行交叉组合
import os
from PyPDF2 import PdfFileMergeraddress=[]
# '08答案卡pdf',
all=['09任务卡pdf','05操作卡pdf']
for y in all:new=path+fr'\{y}'   file_new = [os.path.join(new, f) for f in os.listdir(new)]# print(file_new)address.append(file_new)
print(address)# 推导公式
combinations = [[x, y] for x in address[0] for y in address[1]]
print(combinations)import PyPDF2for files in combinations:print(files)pdf_merger = PyPDF2.PdfFileMerger()for file in files:pdf_merger.append(file)output_file = path+fr"\动物{hs}宫格(无答案) {files[0][-9:-4] } {files[1][-9:-4] }.pdf"pdf_merger.write(output_file)pdf_merger.close()# 有答案:对08、09、05、文件夹(每份3个文件),进行交叉组合import os
from PyPDF2 import PdfFileMergeraddress=[]all=['08答案卡pdf','09任务卡pdf','05操作卡pdf']
for y in all:new=path+fr'\{y}'   file_new = [os.path.join(new, f) for f in os.listdir(new)]# print(file_new)address.append(file_new)
print(address)
print(len(address))# 推导公式
combinations = []for i in address[0]:for j in address[1]:for k in address[2]:combinations.append([i, j, k])
print(combinations)
print(len(combinations))import PyPDF2for files in combinations:print(files)pdf_merger = PyPDF2.PdfFileMerger()for file in files:pdf_merger.append(file)output_file = path+fr"\动物{hs}宫格(有答案) {files[0][-9:-4] } {files[1][-9:-4]} {files[2][-9:-4]}.pdf"pdf_merger.write(output_file)pdf_merger.close()# 删除答案卡任务卡样式不一致的import os
import shutil# 遍历文件夹下的所有文件
for file_name in os.listdir(path):# 检查文件是否为PDF格式if file_name.endswith(".pdf"):# 获取文件名前五个字符# 判断文件名是否符合条件if  "动物4宫格(有答案)" in file_name:# 读取PDF文件内容# with open(os.path.join(folder_path, file_name), 'rb') as f:#     content = f.read()# 检查第10和第15个字符是否相同if file_name[-15] == file_name[-21]:# 保留符合条件的PDF文件print(f"保留文件:{file_name}")else:# 删除不符合条件的PDF文件os.remove(os.path.join(path, file_name))print(f"删除文件:{file_name}")# imagePath11=path+r'\08答案卡pdf'
# imagePath22=path+r'\09任务卡pdf'
# imagePath=path+r'\零时Word'
# imagePatha=path+r'\06答案卡'
# imagePathq=path+r'\07任务卡'
# imagePathpaste=path+r'\05操作卡pdf'shutil.rmtree(imagePath11) #递归删除文件夹,即:删除非空文件夹   
shutil.rmtree(imagePath22) #递归删除文件夹,即:删除非空文件夹
# shutil.rmtree(imagePath) #递归删除文件夹,即:删除非空文件夹
shutil.rmtree(imagePatha) #递归删除文件夹,即:删除非空文件夹
shutil.rmtree(imagePathq) #递归删除文件夹,即:删除非空文件
shutil.rmtree(imagePathpaste)

代码解析:

1.制作动物操作卡(大图片卡一页1图、1页2图 一页6图)

四张动物图片(尽量是正方形)

生成三款图案大小不同的操作卡

01图操作卡:1页1张图片,共16张纸

02图操作卡:1页1张图片,共8张纸

06图操作卡:1页6张图片,共3张纸,一共16张动物(4*4)

2.、第二板块、动物任务卡和答案卡一套,只要JPG

这一步就是生成数独底图,时间很长很长……等的快崩溃了,直接看最后效果答案卡和任务卡图片

06答案卡

07任务卡

每张图片大约800KB

这些宝贵的图片是生成各种尺寸任务卡、答案卡的基础!!!

3、第三板块、把动物任务卡和答案卡一套分别做成1页1份,1页2份,1页6份的pdf

把图片插入不同word模版.制作答案卡PDF和任务卡PDF

08答案卡

01图答案卡16页(最大)公开课

02图答案卡8页(最适合)区角个别化

03图答案卡3页(最小)节省打印纸和彩墨

 09任务卡

01图任务卡16页(最大)公开课

02图任务卡8页(最适合)区角个别化

03图任务卡3页(最小)节省打印纸

到这里,所有的素材都准备好了

4、第四板块、交叉合并有答案6套,无答案6套(1-1-1、1-1,1-2-2,1-2,2-1-1,2-1……----')

最后就是对三个文件里的3个文件进行两两组合、三三组合(推导公式)

A:无答案的:两两组合(9套)

B:无答案的:三三组合(27套)

B:无答案的:需要任务卡和答案卡一样大小,删除数字不相等的pdf(9套)

举例:

由此完成了9*9种数独善品规格的制作。


http://www.mrgr.cn/news/34147.html

相关文章:

  • 外包干了4年,技术退步太明显了。。。。。
  • 防火墙详解(一) 网络防火墙简介
  • 导致mfc140u.dll,无法继续执行代码的原因分析及解决方法
  • 数据安全治理
  • 华为防火墙配置双机热备
  • netstat 命令:网络监控
  • 发票查验API接口是什么?发票查验接口用python demo示例如何集成
  • hCaptcha 图像识别 API 对接说明
  • 【Go】Go语言切片(Slice)深度剖析与应用实战
  • 三边法定位与三点法定位 辨析
  • [arcgis插件]在批量出图时,如何把图层属性表以动态表格的形式插入到布局页面
  • Qt 窗口类的继承关系和作用
  • 【C++】类与对象(上篇)
  • Qt --- 常用控件的介绍 --- 其他控件
  • C#和数据库高级:抽象类和抽象方法
  • 成功案例|大模型备案全网最详细办理流程
  • TypeScript-面向对象(接口、类、对象、泛型)
  • Docker使用指南
  • 计量校准中测量溯源性是什么?已校准设备要怎么处理?
  • 【机器学习】揭秘GBDT:梯度提升决策树