import random, os
import PySimpleGUI as sg
from docx import Document
from docx.shared import RGBColor, Pt, Mm, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
'''
该程序产生口算题doc文件:
'''
document = Document()
'''
生成随机数,默认产生2位数的随机数
'''
def randomtoNUM(bit=2):
if bit == 2:
return random.randint(10, 99)
elif bit == 3:
return random.randint(100, 999)
elif bit == 1:
return random.randint(1, 9)
'''
2位数减法(含退位)
'''
def chutijian():
jia1_10 = random.randint(1, 9)
jia1_1 = random.randint(0, 8)
jia1 = int(str(jia1_10) + str(jia1_1))
# print(8-int(str(jia1)[0]))
jia2_max10 = int(str(jia1)[0]) - 1
if jia2_max10 < 1:
jia2_10 = jia2_max10
else:
jia2_10 = random.randint(0, jia2_max10)
if int(str(jia1)[1]) + 1 >= 9:
jia2_1 = 9
else:
jia2_1 = random.randint(int(str(jia1)[1]) + 1, 9)
jia2 = int(str(jia2_10) + str(jia2_1))
# print(eval("{} + {}".format(jia1,jia2)))
return "{:<2d} - {:>2d}".format(jia1, jia2)
'''
2位数加法(含进位)
'''
def chutiAdd():
jia1_10 = random.randint(1, 8)
jia1_1 = randomtoNUM(1)
jia1 = int(str(jia1_10) + str(jia1_1))
# print(8-int(str(jia1)[0]))
jia2_max10 = 8 - int(str(jia1)[0])
if jia2_max10 <= 1:
jia2_10 = abs(jia2_max10)
else:
jia2_10 = random.randint(1, jia2_max10)
if 10 - int(str(jia1)[1]) >= 9:
jia2_1 = 9
else:
jia2_1 = random.randint(10 - int(str(jia1)[1]), 9)
jia2 = int(str(jia2_10) + str(jia2_1))
# print(eval("{} + {}".format(jia1,jia2)))
if random.randint(0, 1):
return "{:<2d} + {:>2d}".format(jia1, jia2)
else:
return "{:<2d} + {:>2d}".format(jia2, jia1)
'''
1位数加法(含进位)
'''
def chuti1BitAddH():
jia1 = randomtoNUM(1)
jia2 = 10 - jia1 # 第二个数最小值
if jia2 == 1:
jia2 = 9
else:
jia2 = random.randint(10 - jia1, 9)
if random.randint(0, 1):
return "{:<2d} + {:>2d}".format(jia1, jia2)
else:
return "{:<2d} + {:>2d}".format(jia2, jia1)
'''
1位数加法(不含进位)
'''
def chuti1BitAdd():
jia1 = random.randint(1, 8)
jia2 = 9 - jia1 # 第二个数最大值
if jia2 <= 1:
jia2 = 1
else:
jia2 = random.randint(1, jia2)
if random.randint(0, 1):
return "{:<2d} + {:>2d}".format(jia1, jia2)
else:
return "{:<2d} + {:>2d}".format(jia2, jia1)
'''
1位数减法
'''
def chuti1Bitsub():
jian1 = random.randint(2, 9)
jian2 = jian1 - 1
if jian2 <= 1:
jian2 = 1
else:
jian2 = random.randint(1, jian2)
return "{:<2d} - {:>2d}".format(jian1, jian2)
'''
产生2个相减需退位的数,即第1个数小于第二个数
'''
def gtTenSub():
jia1 = random.randint(0, 8)
jia2 = jia1+1
if jia2 >= 9:
jia2 = 9
else:
jia2 = random.randint(jia2, 9)
return jia1, jia2
'''
产生2个相减不退位的数,第1个数大于第二个数
'''
def ltTenSub():
jia1 = random.randint(2, 9)
jia2 = jia1-1 # 第二个数最大值
if jia2 <= 1:
jia2 = 1
else:
jia2 = random.randint(1, jia2)
return jia1, jia2
'''
产生2个相加进位的数
'''
def gtTen():
jia1 = random.randint(1, 9)
jia2 = 9 - jia1
if jia2 >= 9:
jia2 = 9
else:
jia2 = random.randint(jia2 + 1, 9)
return jia1, jia2
'''
产生2个相加不进位的数
'''
def ltTen():
jia1 = random.randint(1, 8)
jia2 = 9 - jia1 # 第二个数最大值
if jia2 <= 1:
jia2 = 1
else:
jia2 = random.randint(1, jia2)
return jia1, jia2
'''
3位数相加
'''
def chuti3BitAdd():
listone = []
listtwo = []
gttenNum = random.randint(1, 3) # 选出需要进位的个数
for i in range(gttenNum):
one, two = gtTen()
listone.append(str(one))
listtwo.append(str(two))
for j in range(3 - gttenNum):
one, two = ltTen()
listone.append(str(one))
listtwo.append(str(two))
#print('完整:', ''.join(listone), ''.join(listtwo))
if random.randint(0, 1):
return "{:>8s} \n+ {:>5s}\n ̄ ̄ ̄ ̄ ̄\n\n".format(''.join(listone), ''.join(listtwo))
else:
return "{:>8s} \n+ {:>5s}\n ̄ ̄ ̄ ̄ ̄\n\n".format(''.join(listtwo), ''.join(listone))
'''
3位数相减
'''
def chuti3BitSub():
listone = []
listtwo = []
gttenNum = random.randint(1, 2) # 选出需要退位的个数
for i in range(gttenNum):
one, two = gtTenSub()
listone.append(str(one))
listtwo.append(str(two))
for j in range(3 - gttenNum):
one, two = ltTenSub()
listone.append(str(one))
listtwo.append(str(two))
#print('完整:', ''.join(listone), ''.join(listtwo))
listone.reverse()
listtwo.reverse()
return "{:>8s} \n- {:>5d}\n ̄ ̄ ̄ ̄ ̄\n\n".format(''.join(listone), int(''.join(listtwo)))
'''
整十或整百加减
'''
def allplugsub():
localhandleFunctionlist = ['chuti1BitAdd', 'chuti1BitAddH', 'chuti1Bitsub', 'chutiAdd', 'chutijian']
resulttemp = eval(random.choice(localhandleFunctionlist) + "()")
strarr = resulttemp.split('-')
isFlagplugsub = len(strarr) # 是1为加法,2为减法
beishu = random.choice(['0', '00'])
if isFlagplugsub == 2: # 减法
jian1 = strarr[0].strip() + beishu
jian2 = strarr[1].strip() + beishu
return "{:<2d} - {:>2d}".format(int(jian1), int(jian2))
else: # 加法
strarr = resulttemp.split('+')
jia1 = strarr[0].strip() + beishu
jia2 = strarr[1].strip() + beishu
if random.randint(0, 1):
return "{:<2d} + {:>2d}".format(int(jia1), int(jia2))
else:
return "{:<2d} + {:>2d}".format(int(jia2), int(jia1))
'''
产生doc文档
'''
def makedoc(handlelist,pagenum):
'''
p = document.add_paragraph()
p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run(u'小学生计算题练习 ')
run.font.color.rgb = RGBColor(0, 0, 0)
run.font.size = Pt(28)
p.space_before = Pt(40)
p.add_run().add_break(break_type=6)
'''
document.styles['Normal'].font.name = u'宋体'
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
document.styles['Normal'].font.size = Pt(16)
ti = document.add_paragraph()
ti.alignment = WD_ALIGN_PARAGRAPH.LEFT
for nump in range(pagenum):
tishu = 45
if len(handlelist) ==1 and ('chuti3BitAdd' in handlelist or 'chuti3BitSub' in handlelist):
tishu = 21
if len(handlelist) ==2 and ('chuti3BitAdd' in handlelist and 'chuti3BitSub' in handlelist):
tishu = 21
for i in range(tishu): # 产生45题口算题
# 根据函数名称随机选择题目类型,handlelist list的值,可用的函数'chutiAdd', 'chutijian','chuti1BitAddH','chuti1BitAdd'
if tishu == 45:
content = u"{:<7}=".format(eval(random.choice(handlelist) + "()"))
run1 = ti.add_run("{:<40}".format(content))
elif tishu == 21:
content = u"{}".format(eval(random.choice(handlelist) + "()"))
if i==20 and nump==pagenum-1:
content=content.strip('\n\n')
run1 = ti.add_run("{}".format(content))
run1.font.color.rgb = RGBColor(0, 0, 0)
run1.font.size = Pt(16)
if tishu == 45:
ti.paragraph_format.line_spacing = Pt(45)
#print(len(document.sections))
for section in document.sections:
header = section.header
paragraph = header.paragraphs[0]
paragraph.text = ' 小学生计算题练习 '
paragraph.style = document.styles["Header"]
section.top_margin = Inches(0.7)
section.bottom_margin = Inches(0.7)
section.left_margin = Inches(0.7)
section.right_margin = Inches(0.7)
# Columns = 1
sectPr = section._sectPr
cols = sectPr.xpath('./w:cols')[0]
cols.set(qn('w:num'), '3')
document.save('test.docx') # 可以设置其他路径
os.startfile("test.docx")
# ff GreenTan
sg.ChangeLookAndFeel('LightGreen')
ok_btn = sg.SimpleButton('生成习题', size=(10, 2), font=("微软雅黑", 12), button_color=('white', 'firebrick3'))
cancel_btn = sg.Button('关闭程序', size=(10, 2), font=("微软雅黑", 12))
layout = [
[sg.Checkbox('1位数加,不进位', default=False, size=(35, 2), font=("微软雅黑", 12))],
[sg.Checkbox('1位数加,进位', size=(35, 2), font=("微软雅黑", 12))],
[sg.Checkbox('1位数减', size=(35, 2), font=("微软雅黑", 12))],
[sg.Checkbox('2位数加,进位', size=(35, 2), font=("微软雅黑", 12))],
[sg.Checkbox('2位数减,退位', size=(35, 2), font=("微软雅黑", 12))],
[sg.Checkbox('整十或整百加减', size=(35, 2), font=("微软雅黑", 12))],
[sg.Checkbox('3位数相加,进位,只能与竖式同时选择', size=(35, 2),text_color=('blue'), font=("微软雅黑", 12))],
[sg.Checkbox('3位数减法,退位,只能与竖式同时选择', size=(35, 2),text_color=('blue'), font=("微软雅黑", 12))],
# [sg.Slider(range=(1,5), orientation='h',size=(35, 10), font=("微软雅黑", 12))],
#[sg.Text('This is some text', font='Courier 12', text_color='blue', background_color='green')],
#[sg.Spin([1,2,3,4,5], size=(35, 10), font=("微软雅黑", 12))],
[sg.Text('要生成几页:',auto_size_text=True,size=(15, 1), font=("微软雅黑", 12))],
[sg.Slider(range=(1,6), orientation='h',size=(35, 15), font=("微软雅黑", 12))],
[ok_btn, cancel_btn],[sg.StatusBar('好好学习,天天向上\n编写语言:python ',size=(400,10), font=("微软雅黑", 12))]
]
window = sg.Window('小学生计算题生成器', default_element_size=(40, 2), size=(400, 485)).Layout(layout)
handleFunctionlist = ['chuti1BitAdd', 'chuti1BitAddH', 'chuti1Bitsub', 'chutiAdd', 'chutijian', 'allplugsub',
'chuti3BitAdd','chuti3BitSub']
while True:
event, values = window.read()
if event in (None, '关闭程序'):
# User closed the Window or hit the Cancel button
break
elif event in (None, '生成习题'):
# sg.Popup(event, values)
handlelist = []
#print(values)
for i in values:
if type(values[i])==bool and values[i]:
handlelist.append(handleFunctionlist[i])
#print(handlelist)
pagenum=int(values[8])
#print(pagenum)
makedoc(handlelist,pagenum)
break
window.close()
解决方法:Python运行时报错 ModuleNotFoundError: No module named ‘exceptions’
import random
class Student():
#初始化
def __init__(self):
self.__name='' #姓名
self.__city='' #城市
self.__school='' #学校
self.__height=0 #身高
self.__weight=0 #体重
self.__breast='' #罩杯
self.__score=0 #高考分数
self.__subject='' #选修科目
self.__level='' #选修等第
#设立身高体重
def build_body(self):
self.__height=random.randint(158,176)
temp_height=self.__height/100
BMI=random.uniform(18,21)
self.__weight=int(BMI*temp_height*temp_height)
flag1=random.randint(1,20)
if 158<=self.__height<=163:
if 1<=flag1<=14:self.__breast='A'
else:self.__breast='B'
elif 164<=self.__height<=170:
if 1<=flag1<=8:self.__breast='A'
elif 9<=flag1<=17:self.__breast='B'
else:self.__breast='C'
else:
if 1<=flag1<=3:self.__breast='A'
elif 4<=flag1<=12:self.__breast='B'
elif 13<=flag1<=18:self.__breast='C'
else:self.__breast='D'
#随机设立成绩
def create_score(self):
self.__score=random.randint(301,400)
#设立必修等级
def create_level(self):
subject=['政史','史地','物化','物生','物地']
level=['C','C','B','B+','A','A+','A+']
self.__subject=subject[random.randint(0,4)]
flag1=0
if 300<self.__score<=320:flag1=1
elif 320<self.__score<=340:flag1=2
elif 340<self.__score<=360:flag1=3
elif 360<self.__score<=380:flag1=4
else:flag1=5
flag2=flag1+random.randint(-1,0)
self.__level=level[flag1]+level[flag2]
#设立姓名
def set_name(self,name):
self.__name=name
#设立学校
def set_school(self):
city_list=[]
school_list=[]
with open(r'school_list\readme.txt') as file1:
for city in file1:
city_list.append(city.strip())
flag1=random.randint(0,12)
self.__city=city_list[flag1]
file_name=r"school_list"+ "\\" +str(flag1+1)+'.txt'
with open(file_name) as file2:
for school in file2:
school_list.append(school.strip())
flag2=random.randint(0,len(school_list)-1)
self.__school=school_list[flag2]
#打印结果
def show(self):
inf='姓名:' +self.__name
inf+=' 身高:'+str(self.__height)+'cm'
inf+=' 体重:'+str(self.__weight)+'kg'
inf+=' 罩杯:'+self.__breast
inf+=' 城市:'+self.__city
inf+=' 学校:'+self.__school
inf+=' 高考成绩:'+str(self.__score)
inf+=' 选科:'+self.__subject
inf+=' 等第:'+self.__level
return inf
from function import Student
import random
#名字初始化
xing=[]
ming=[]
with open(r"name_list\xingshi.txt") as file1:
for line in file1:
xing.append(line.strip())
lx=len(xing)
with open(r"name_list\mingzi.txt") as file2:
for line in file2:
ming.append(line.strip())
lm=len(ming)
#循环(暂时500个)
num=input("输入你想生成的学生信息数量:")
with open("inf.txt",'a') as file3:
for i in range(int(num)):
t=Student()
#名字
flag1=random.randint(1,lx)-1
flag2=random.randint(1,lm)-1
t.set_name(xing[flag1]+ming[flag2])
#其他
t.build_body()
t.create_score()
t.create_level()
t.set_school()
inf=t.show()
file3.write(inf+'\n')
print("已生成!")
输入数量,自动生成到主目录的inf.txt
打开inf.txt:
import random
def generateWish1():
list1=['椒花献颂,','春回柳叶,','天开淑景,','地暖春风,','天高地阔,','风光胜旧,','岁序更新,','天翔紫燕,','喜鹊鸣春,','花香四季,','月满一轮,','花迎春光,','牛耕绿野,','江山秀丽,','虎啸青山,','无边春舍,',
'有福人家,','龙吟国瑞,','虎啸年丰,','龙兴华夏,','百花献瑞,','百花齐放,','岁且更始,','时乃日新,','莺歌燕舞,','春光骀荡,','万物回春,','国光蔚起,','民气昭苏,','国步龙腾,','天开化宇,']
s=random.choice(list1)
list1.remove(s)#删除已被选择的元素,以免重复,下同
return s
#这个列表是套话
def generateWish2():
list2=['学业有成,','福星高照,','万事如意,','日月皆春,','江山永固,','福寿安康,','岁岁平安,','年年有余,','腰缠万贯,','财源亨通,','金玉满堂,','喜气洋洋,','万事如意,','大吉大利,','三阳开泰,','财源广进,',
'四时喜庆,','五谷丰登,','四时如意,','万事遂心,','燕舞新春,','平安无恙,','吉庆有余,','福星高照,','恭贺新春,','吉庆有余,','福享新春,','喜气盈门,','三阳开泰,','励精图治,','革故鼎新,','抬头见喜,','吉星高照,','恭喜发财,','心想事成,','五福临门,','五谷丰登,','门凝瑞霭,','户发春光,',
'人寿年丰,','人乐丰年,','一门瑞气,','万里春风,','千祥云集,','百福骈臻,','人登寿域,','世跻春台,','万马奔腾,','满院春光,','庆云跃日,','金玉满堂,','龙凤呈祥,','百业兴旺,','吉星高照,','吉祥如意,','开春大吉,','五谷丰登,','万事顺利,','万事顺意,','六蓄兴旺,','荣华富贵,','金玉满堂,',
'鹏程万里,','笑逐颜开,','心旷神怡,','财源广进,','阖家欢乐,','飞黄腾达,','万事顺意,','幸福美满,','官运亨通,','美梦连连,','万事顺利,','龙凤呈祥,','红红火火,','二龙腾飞,','三阳开泰,','四季平安,','五福临门,','六六大顺,','七星高照,','八方来财,','九九同心,','一帆风顺,']
s=random.choice(list2)
list2.remove(s)
return s
#这个列表是各种祝福语
if __name__ == '__main__':
name=input("Please input the person's name:")
string='牛年新春将至,'
i=0
for i in range (0,3):#这里默认选择3个成语,可自行调整
string+=generateWish1()
i+=1
string1=list(string)#字符串转列表
string1[-1]='。' #将此部分的逗号转换为句号,使句意通顺,下同
string=''.join(string1) #列表转回字符串
s1=name+',在新的一年里,祝你'
string+=s1
for i in range (0,5):
string+=generateWish2()
i+=1
string1=list(string) #字符串转列表
string1[-1]='!'
string=''.join(string1)
print(string)