大象关进冰箱需要两步走:
获取word文件内容 将获取的内容拆分为对应的业务字段并写入sqlite中
首先我这有个文档,里面包含了驾照考试科四试题。
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/6d81800a19d8bc3ee3f0633e898ba61ea9d3454d?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
然后新建sqlite表,以下为表结构:
CREATE TABLE "myDocAnswer" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"title" TEXT,
"a" TEXT,
"b" TEXT,
"c" TEXT,
"d" TEXT,
"answer" TEXT
);
最后将数据导入sqlite中,以下为完整代码:
import docx
import sqlite3
'''
读取docx 数据
'''
document = docx.Document("question.docx")
data=[] # 定义data列表
item={}
#输出每一段的内容
for param in document.paragraphs:
# print(param.text)
if param.text:
i=param.text[0]
if i.isdigit():
item['title']=param.text
if i=='A':
item['a'] = param.text[2:]
if i=='B':
item['b'] =param.text[2:]
if i=='C':
item['c'] = param.text[2:]
if i=='D':
item['d'] =param.text[2:]
if i=='标':
item['answer'] = param.text[-1:]
else:
data.append(item)
item={}
'''
写入 sqlite
'''
conn = sqlite3.connect("mydocAnswer.db")
c = conn.cursor()
for items in data:
c.execute("INSERT INTO `myDocAnswer` (`title`,`a`,`b`,`c`,`d`,`answer`) VALUES ('" + items['title'] + "', '" + items['a'] + "', '" + items['b'] + "', '" + items['c'] + "', '" + items['d'] + "', '" + items['answer'] + "')");
conn.commit()
conn.close()
print('finish')
运行后查看sqlite数据表数据:
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/9345d688d43f8794d7a52fdad91b0ef41ad53aef?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)