1 #docx文档题库包含很多段,每段一个题目,格式为:问题。(答案)
2 #数据库datase.db中tiku表包含kechengmingcheng、zhanngji、timu、daan四个字段
3 import sqlite3
4 from docx import Document
5
6 doc = Document('《Python程序设计》题库.docx')
7
8 #连接数据库
9 conn = sqlite3.connect('database.db')
10 cur = conn.cursor()
11
12 #先清空原来的题目,可选操作
13 # cur.execute('delete from tiku')
14 # conn.commit()
15
16 for p in doc.paragraphs:
17 text = p.text
18 if '(' in text and ')'in text:
19 index = text.index('(')
20 #分离问题和答案
21 question=text[:index]
22 if '___' in question:
23 question = '填空题:' + question
24 else:
25 question = '判断题:' + question
26 answer=text[index+1:-1]
27 #将数据写入数据库
28 sql = 'insert into tiku(kechengmingcheng,zhanngji,timu,daan)values("Python程序设计","未分类","'+question+'","'+answer+'")'
29 cur.execute(sql)
30 conn.commit()
31 #关闭数据库连接
32 conn.close()