Python_doc文件写入SQLite数据库

时间:2023-03-09 22:31:51
Python_doc文件写入SQLite数据库
 #docx文档题库包含很多段,每段一个题目,格式为:问题。(答案)
#数据库datase.db中tiku表包含kechengmingcheng、zhanngji、timu、daan四个字段
import sqlite3
from docx import Document doc = Document('《Python程序设计》题库.docx') #连接数据库
conn = sqlite3.connect('database.db')
cur = conn.cursor() #先清空原来的题目,可选操作
# cur.execute('delete from tiku')
# conn.commit() 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,zhanngji,timu,daan)values("Python程序设计","未分类","'+question+'","'+answer+'")'
cur.execute(sql)
conn.commit()
#关闭数据库连接
conn.close()