gpt4 book ai didi

python - 填充表,其中每列来自文本文件的不同行

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:21 26 4
gpt4 key购买 nike

我有一个txt文件,其中一些行包含字符串,另一些行包含值。这些值对应“属于”上一行。例如:

+'aaa'
+'bbb'
*value1
*value2
+'ccc'
*value3
+'ddd'

等等。我正在尝试创建一个表,其中第一列包含包含字符串的行,第二列包含包含值的行。我的问题是,如果字符串具有相应的值,则字符串和值(列表)位于同一行。如果字符串没有相应的值,我希望它与 NULL 位于同一行。类似这样的:

column1  |      column2
-----------------------------
+'aaa' | NULL
+'bbb' | [*value1 ,*value2]
+'ccc' | [*value3]
+'ddd' | NULL
etc

我尝试做这样的事情:

import sqlite3
db=sqlite3.connect('mydatabase.db')
cur=db.cursor()
cur.execute('CREATE TABLE mytable (mystrings TEXT, myvalues TEXT)')
with open('myfile.txt') as f:
for line in f.readlines():
if line.startswith('+'):
cur.execute("INSERT INTO mytable VALUES(?))",line)
if line.startswith('*'):
cur.execute("INSERT INTO mytable VALUES(?))",line)
db.commit()
db.close()

但显然这是不对的,因为 mytable 有两个值。

最佳答案

您不能一找到值就简单地插入它们。至少您应该插入一行仅包含 mystrings 列,然后在找到 myvalues 时进行更新。但是,由于每个字符串可能有多个值,因此存储键和值并执行一次插入非常简单:

import sqlite3

def createtable(dbname):
db=sqlite3.connect(dbname)
cur=db.cursor()
cur.execute('CREATE TABLE mytable (mystrings TEXT, myvalues TEXT)')
cur.close()
db.close()


def dropdb(dbname):
db=sqlite3.connect(dbname)
cur=db.cursor()
cur.execute('DROP TABLE mytable')
cur.close()
db.close()

def insert(cur, key, val):
if key is not None:
if len(val) == 0:
value = None
elif len(val) == 1:
value = val[0]
else:
value = str(val)
# print "INSERT", key, value
cur.execute("INSERT INTO mytable VALUES(?, ?)", (key, value))

def trt(filename, dbname):
key = None
val = None
db = sqlite3.connect(dbname)
cur = db.cursor()
try:
with open(filename) as f:
for line in f:
if line.startswith('+'):
if key is not None:
if len(val) == 0:
value = None
elif len(val) == 1:
value = val[0]
else:
value = str(val)
insert(cur, key, val)
print "key", line[:-1]
key = line[:-1]
val = []
else:
print "value", line[:-1]
if val is None:
print "Value before first string : ignored"
else:
val.append(line[:-1])
insert(cur, key, val)
finally:
cur.close()
db.commit()
db.close()

createdb('mydatabase.db')
trt('myfile.txt', 'mydatabase.db')

关于python - 填充表,其中每列来自文本文件的不同行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26600526/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com