Python+MySQL 무 작위 시험지 및 답안 생 성 프로그램의 예시 코드

배경
이 글 은 Python 을 사용 하여 MySQL 데이터베이스 에서 시험 문 제 를 추출 하 는 방법 을 공유 하고 생 성 된 시험지 가 각각 다르다.
준비 작업
1.Python 3 설치
다운로드 주소:https://www.python.org/downloads/windows/
2.설치 라 이브 러 리
pip installpython-docx==0.8.10
pip installPyMySQL==1.0.2
3.시험 문제 집.xlsx
프로그램 을 개발 하기 전에 먼저 시험 문 제 를 수집 해 야 합 니 다.본 고 는 시험 문 제 를 수집 하여 MySQL 데이터베이스 에 저장 하 는 것 입 니 다.형식 은 다음 과 같 습 니 다.
선택 문제 데이터베이스 캡 처:

빈 문제/풀이/종합 문제 데이터베이스 캡 처:

코드
Python+MySQL 무 작위 시험지 및 답안 생 성 프로그램.py

# _*_ coding:utf-8 _*_
import random,os,pymysql
from docx import Document
from docx.shared import Inches,Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH,WD_LINE_SPACING
from docx.oxml.ns import qn
from docx.shared import Inches

class SunckSql():
 def __init__(self, host, user, passwd, dbName='', charset='utf8'):
  self.host = host
  self.user = user
  self.passwd = passwd
  self.dbName = dbName
  self.charset = charset

 def connet(self):
  self.db = pymysql.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.dbName,
         charset=self.charset) #      
  self.cursor = self.db.cursor() #       

 def close(self):
  self.cursor.close() #     
  self.db.close() #        

 #   
 def get_all(self, sql):
  res = None
  try:
   self.connet()
   self.cursor.execute(sql) #   sql  
   res = self.cursor.fetchall() #         
  except Exception as e:
   print('    :%s' % e)
  finally:
   self.close()
  return res

 #   、  、  
 def shell_sql(self, sql):
  "  sql  "
  print(sql)
  count = 0
  try:
   self.connet()
   count = self.cursor.execute(sql) #   sql  
   self.db.commit() #   
  except Exception as e:
   print('      :%s' % e)
   self.db.rollback() #       ,        
  finally:
   self.close()
  return count

def router_docx(choice1='', choice2='', choice3='', choice5='', choice6='', choice7='',paper_path='',name='1'):
 "             "
 docx1 = Document()
 docx2 = Document()
 docx1.styles['Normal'].font.name = '  '         #    
 docx1.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '  ') #    
 docx1.styles['Normal'].font.size = Pt(11)        #      
 docx1.styles['Normal'].paragraph_format.space_before = Pt(0)    #      
 docx1.styles['Normal'].paragraph_format.space_after = Pt(0)    #      
 docx1.styles['Normal'].paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE #      
 sec = docx1.sections[0]             # sections      “ ”
 sec.left_margin = Inches(1)            #        
 sec.right_margin = Inches(1)            #       
 sec.top_margin = Inches(0.5)            #        
 sec.bottom_margin = Inches(0.5)           #       

 p=docx1.add_paragraph()             #    
 run = p.add_run('    (    )    (%s)' % name)      #  add_run    
 run.font.name = '    '             #    
 run._element.rPr.rFonts.set(qn('w:eastAsia'), '    ')     #    
 run.font.size = Pt(18)             #      
 p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER     #        
 docx1.add_paragraph('【  】')           #       
 docx1.add_paragraph('1.     60  。')
 docx1.add_paragraph('2.          ,                 。')
 q=docx2.add_paragraph()             #    
 run = q.add_run('    (    )      (%s)' % name)     #  add_run    
 run.font.name = '    '             #    
 run._element.rPr.rFonts.set(qn('w:eastAsia'), '    ')     #    
 run.font.size = Pt(18)             #      
 q.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER     #        

 p1 = docx1.add_paragraph()
 p1.paragraph_format.space_before = Pt(12)        #      
 docx2.add_paragraph(' 、   ')
 run = p1.add_run(' 、   (  3  45 )')
 run.bold = True               #     
 list1=random.sample(range(0,len(choice1)-1),3)       #len          
 x=1
 for y in list1:
  docx1.add_paragraph(str(x)+'、'+choice1[y][1])
  docx1.add_paragraph(choice1[y][2])
  docx1.add_paragraph(choice1[y][3])
  docx1.add_paragraph(choice1[y][4])
  p11=docx1.add_paragraph(choice1[y][5])
  p11.paragraph_format.space_after = Pt(12)       #    
  docx2.add_paragraph(str(x)+'、'+choice1[y][6])
  x+=1

 list2=random.sample(range(0,len(choice2)-1),7)
 x=1
 for y in list2:
  docx1.add_paragraph(str(x+3)+'、'+choice2[y][1])
  docx1.add_paragraph(choice2[y][2])
  docx1.add_paragraph(choice2[y][3])
  docx1.add_paragraph(choice2[y][4])
  p11=docx1.add_paragraph(choice2[y][5])
  p11.paragraph_format.space_after = Pt(12)
  docx2.add_paragraph(str(x+3)+'、'+choice2[y][6])
  x+=1

 list3=random.sample(range(0,len(choice3)-1),5)
 x=1
 for y in list3:
  docx1.add_paragraph(str(x+10)+'、'+choice3[y][1])
  docx1.add_paragraph(choice3[y][2])
  docx1.add_paragraph(choice3[y][3])
  docx1.add_paragraph(choice3[y][4])
  p11=docx1.add_paragraph(choice3[y][5])
  p11.paragraph_format.space_after = Pt(12)
  docx2.add_paragraph(str(x+10)+'、'+choice3[y][6])
  x+=1

 p2 = docx1.add_paragraph()
 p2.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph(' 、   ')
 run = p2.add_run(' 、   (  3 , 15 )')
 run.bold = True
 list2 = random.sample(range(0, len(choice5)-1), 5)
 i = 1
 for j in list2:
  docx1.add_paragraph(str(i) + '、' + choice5[j][1])
  docx2.add_paragraph(str(i) + '、' + str(choice5[j][2]))
  i += 1

 p3 = docx1.add_paragraph()
 p3.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph(' 、   ')
 run = p3.add_run(' 、   (  10 , 20 )')
 run.bold = True
 list3 = random.sample(range(0, len(choice6)-1), 2)
 n = 1
 for m in list3:
  docx1.add_paragraph(str(n) + '、' + choice6[m][1])
  docx1.add_paragraph('\r')
  docx2.add_paragraph(str(n) + '、' + choice6[m][2])
  n += 1

 p4 = docx1.add_paragraph()
 p4.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph(' 、   ')
 run = p4.add_run(' 、   ( 20 )')
 run.bold = True
 list4 = random.randint(0, len(choice7)-1)
 docx1.add_paragraph('1、' + choice7[list4][1])
 docx2.add_paragraph(choice7[list4][2])

 docx1.save(os.path.join(paper_path, '      (%s).docx' % name))    #    
 docx2.save(os.path.join(paper_path, '        (%s).docx' % name))   #    

def android_docx(choice1, choice2, choice4, choice5, choice6, choice8,paper_path,name):
 """           """
 docx1 = Document()
 docx2 = Document()
 docx1.styles['Normal'].font.name = '  '          #    
 docx1.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '  ')   #    
 docx1.styles['Normal'].font.size = Pt(11)          #      
 docx1.styles['Normal'].paragraph_format.space_before = Pt(0)     #      
 docx1.styles['Normal'].paragraph_format.space_after = Pt(0)      #      
 docx1.styles['Normal'].paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE #      
 sec = docx1.sections[0]               # sections      “ ”
 sec.left_margin = Inches(1)              #        
 sec.right_margin = Inches(1)             #       
 sec.top_margin = Inches(0.5)             #        
 sec.bottom_margin = Inches(0.5)             #       

 p=docx1.add_paragraph()               #    
 run = p.add_run('    (    )    (%s)' % name)        #  add_run    
 run.font.name = '    '              #    
 run._element.rPr.rFonts.set(qn('w:eastAsia'), '    ')       #    
 run.font.size = Pt(18)               #      
 p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER      #        
 docx1.add_paragraph('【  】')             #       
 docx1.add_paragraph('1.     60  。')
 docx1.add_paragraph('2.          ,                 。')
 q = docx2.add_paragraph()              #     
 run = q.add_run('    (    )      (%s)' % name)       #   add_run    
 run.font.name = '    '              #     
 run._element.rPr.rFonts.set(qn('w:eastAsia'), '    ')       #     
 run.font.size = Pt(18)               #       
 q.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER      #         

 p1 = docx1.add_paragraph()
 p1.paragraph_format.space_before = Pt(12)          #      
 docx2.add_paragraph(' 、   ')
 run = p1.add_run(' 、   (  3  45 )')
 run.bold = True                 #     
 list1=random.sample(range(0,len(choice1)-1),3)
 x=1
 for y in list1:
  docx1.add_paragraph(str(x)+'、'+choice1[y][1])
  docx1.add_paragraph(choice1[y][2])
  docx1.add_paragraph(choice1[y][3])
  docx1.add_paragraph(choice1[y][4])
  p11=docx1.add_paragraph(choice1[y][5])
  p11.paragraph_format.space_after = Pt(12)         #    
  docx2.add_paragraph(str(x)+'、'+choice1[y][6])
  x+=1

 list2=random.sample(range(0,len(choice2)-1),7)
 x=1
 for y in list2:
  docx1.add_paragraph(str(x+3)+'、'+choice2[y][1])
  docx1.add_paragraph(choice2[y][2])
  docx1.add_paragraph(choice2[y][3])
  docx1.add_paragraph(choice2[y][4])
  p11=docx1.add_paragraph(choice2[y][5])
  p11.paragraph_format.space_after = Pt(12)
  docx2.add_paragraph(str(x+3)+'、'+choice2[y][6])
  x+=1

 list3=random.sample(range(0,len(choice4)-1),5)
 x=1
 for y in list3:
  docx1.add_paragraph(str(x+10)+'、'+choice4[y][1])
  docx1.add_paragraph(choice4[y][2])
  docx1.add_paragraph(choice4[y][3])
  docx1.add_paragraph(choice4[y][4])
  p11=docx1.add_paragraph(choice4[y][5])
  p11.paragraph_format.space_after = Pt(12)
  docx2.add_paragraph(str(x+10)+'、'+choice4[y][6])
  x+=1

 p2 = docx1.add_paragraph()
 p2.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph(' 、   ')
 run = p2.add_run(' 、   (  3 , 15 )')
 run.bold = True
 list2 = random.sample(range(0, len(choice5)-1), 5)
 i = 1
 for j in list2:
  docx1.add_paragraph(str(i) + '、' + choice5[j][1])
  docx2.add_paragraph(str(i) + '、' + str(choice5[j][2]))
  i += 1

 p3 = docx1.add_paragraph()
 p3.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph(' 、   ')
 run = p3.add_run(' 、   (  10 , 20 )')
 run.bold = True
 list3 = random.sample(range(0, len(choice6)-1), 2)
 n = 1
 for m in list3:
  docx1.add_paragraph(str(n) + '、' + choice6[m][1])
  docx1.add_paragraph('\r')
  docx2.add_paragraph(str(n) + '、' + choice6[m][2])
  n += 1

 p4 = docx1.add_paragraph()
 p4.paragraph_format.space_before = Pt(12)
 docx2.add_paragraph(' 、   ')
 run = p4.add_run(' 、   ( 20 )')
 run.bold = True
 list4 = random.randint(0, len(choice8)-1)
 docx1.add_paragraph('1、' + choice8[list4][1])
 docx2.add_paragraph(choice8[list4][2])

 docx1.save(os.path.join(paper_path, '      (%s).docx' % name))
 docx2.save(os.path.join(paper_path, '        (%s).docx' % name))

def main(ip,name,passwd,db_name):
 paper_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '  ') #      
 if not os.path.exists(paper_path):
  os.mkdir(paper_path)              #       
 my = SunckSql(ip,name,passwd,db_name)           #     
 choice1 = my.get_all("select * from %s" % '        ')      #         
 choice2 = my.get_all("select * from %s" % '       ')
 choice3 = my.get_all("select * from %s" % '       ')
 choice4 = my.get_all("select * from %s" % '       ')
 choice5 = my.get_all("select * from %s" % '   ')
 choice6 = my.get_all("select * from %s" % '   ')
 choice7 = my.get_all("select * from %s" % '       ')
 choice8 = my.get_all("select * from %s" % '       ')
 for i in range(1,4):               #    3      
  router_docx(choice1, choice2, choice3, choice5, choice6, choice7, paper_path, i)
  android_docx(choice1, choice2, choice4, choice5, choice6, choice8, paper_path, i)

if __name__ == "__main__":
 main(ip='   ip  ', name='mysql  ', passwd='mysql  ', db_name='       ')
파 이 썬+MySQL 랜 덤 시험지 및 답안 생 성 프로그램 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 파 이 썬 MySQL 랜 덤 시험지 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기