我使用的数据集位于多个文本文件中,格式如下:#*TITLE1
#@AUTHOR1,AUTHOR2
#tYEAR
#cpublicationvenue
#index1
每个方块代表一张纸。在我的数据集中,我有成千上万个这样的块。我要在这个数据库中插入多个表。我在下面写的代码有时非常完美。其他时候,当我试图填充数据库时,它会随机给我一个错误,例如:
^{pr2}$
我现在正处于这样一个阶段,我想把所有这些数据放入我的数据库中,但是我要确保当eg的一个块丢失发布地点行时,代码已经被考虑进去了,在这种情况下,只需在该行中保留该列为空。
这是我写的代码:import MySQLdb
conn = MySQLdb.connect(host="xx", user="xx", db="xx")
db1 = conn.cursor()
with open("path/to/file", "rb") as f:
for line in f:
if line.startswith("#*"):
title = line[2:]
elif line.startswith("#t"):
year = line[2:] # will ignore first two characters of line
elif line.startswith("#c"):
publication_venue = line[2:]
elif line.startswith("#index"):
ID = line[6:]
elif line.startswith("#@"):
author_list = line.split(",")
author_list[0] = author_list[0][2:]
elif line.strip() == '':
db1.execute('''INSERT INTO papers(
ID, TITLE, YEAR, Publication_Venue)
VALUES (%s,%s,%s,%s,%s)''',
(ID, title, year, publication_venue))
for In_order, author in enumerate(author_list, start=1):
In_order = In_order
author = author
db1.execute('''INSERT INTO authors(
ID, AUTHOR, In_order) VALUES(%s,%s,%s)''',
(ID, author, In_order))
conn.commit()
title = None
year = None
publication_venue = None
ID = None
author_list = None
else:
continue
有人能告诉我为什么我得到这个名字错误,因为我已经在我的代码中明确定义了它!!在