用Python把txt导入SQLite3数据库

题库txt:

 
 
 

代码:

import sys
import re
import sqlite3

cx = sqlite3.connect('./avpig_sde.db')  #创建数据库,如果数据库已经存在,则链接数据库;如果数据库不存在,则先创建数据库,再链接该数据库。
cu = cx.cursor()         #定义一个游标,以便获得查询对象。
cu.execute('create table if not exists a41 ([_id] integer PRIMARY KEY AUTOINCREMENT, [content] varchar NOT NULL, [answer] varchar NOT NULL, [parse] varchar, [note] varchar, [type] int NOT NULL, [chapter_id] varchar NOT NULL, [url] VARCHAR)')  #创建表

content_list=[]
anwser_list=[]

# 第一种写法
# patch_file_name="gj_1.txt"
# patch_file=open(patch_file_name,'r')        #打开文档,逐行读取数据
# content=patch_file.read()
# patch_file.close()
# content_list=re.split('[答][案][:][A-D][.]', content)
# #print(content_list)

i = 0
#第二种写法
with open('gj_1.txt','r') as f1:
    contents = f1.read()
    content_list=re.split('[答][案][:][A-D][.]', contents)
    print(content_list)

with open('gj_1.txt','r') as f:
    for line in f:
        index = line.find('答案:')
        print(index)
        if index != -1:#表示没有找到“答案:”
            anwser_list.append(line[int(index+3)])
            print(anwser_list)
            print(content_list[i])
            cu.execute('insert into a41 (_id, content, answer, type, chapter_id) values (?,?, ?,?,?)',(i+1, content_list[i].strip(), anwser_list[i].strip(), 1,"1."))
            i +=1
        #anwser_list.append(list(line.strip('\n').split(','))[0])
# print(anwser_list)
# print(content_list)

cu.close()   #关闭游标
cx.commit()   #事务提交
cx.close()   #关闭数据库

注释:

  1. 首先连接SQLite3数据库
  2. 之前没有数据库就直接用SQL语句创建。
  3. 读txt文件到内存中,读成 list[]
  4. 再用SQL语句导入SQLite3数据库
  5. 关闭数据库
 

知识点:

1.读取txt文件有这里有两种写法,第一种
 
patch_file_name="gj_1.txt” 
patch_file=open(patch_file_name,'r')        #打开文档,逐行读取数据 
content=patch_file.read() 
patch_file.close()
content_list=re.split('[答][案][:][A-D][.]', content)
这里用了正则表达式:
[答][案][:][A-D][.] 表示 匹配 “答案:A到D” 的所有结果。
 
2.读取txt文件的第二种写发, with open
with open('gj_1.txt','r') as f

这种方法不需要再去写close文件的代码,他会自动去close。可以整体读取用read(),输出结果是一个list[]. 也可以用 for … in… 遍历出每个元素。

3.split函数,表示把list按照给出的参数进行分割。    
 content_list=re.split('[答][案][:][A-D][.]', contents)
4.strip()函数,表示去掉字符串两头的空格。
anwser_list[i].strip()

e.g 我是头部空格__我是内容__我是尾部空格.strip() -> 我是内容

猜你喜欢

转载自blog.csdn.net/sirodeng/article/details/104109000