#本文所用的docx文档题库包含很多段,每段一个题目,格式为: 问题。(答案)
#与之对应的数据库datase.db中tiku表包含kechengmingcheng,zhangjie,timu,daan四个字段
#需要先安装扩展库python-docx
import sqlite3
from docx import Document
#打开docx文档
doc = Document('《Python程序设计》题库.docx')
#连接数据库,创建游标
conn = sqlite3.connect('database.db')
cur = conn.cursor()
#先清空原来的题,可选
cur.execute('DELETE FROM tiku')
conn.commit()
#遍历docx文档中所有段的文字
for p in doc.paragraphs:
text = p.text
if '(' in text and ')' in text:
index = text.index('(')
#分离问题和答案
question = text[:index]
if '__' in question:
question = '填空题:' + question
else:
question = '判断题:' + question
answer = text[index+1:-1]
#将数据写入数据库
sql = 'INSERT INTO tiku(kechengmingcheng,zhangjie,timu,daan) VALUES("Python程序设计","未分类","' + question + '","' + answer + '")'
cur.execute(sql)
#提交事务
conn.commit()
#关闭数据库连接
conn.close()
数据导入之后SQLite数据库内容截图(部分):