我将使用的数据集以多个文本文件形式存在,格式如下:
#*TITLE1
#@AUTHOR1,AUTHOR2
#tYEAR
#cpublicationvenue
#index1
每个块代表一篇论文。在我的数据集中,我有成千上万个这样的块。我想将此信息插入到我的数据库中,其中我有多个表。我编写的下面的代码有时候可以完美地工作。但在其他时候,当我尝试填充数据库时,它会随机地给我一个错误,例如:
NameError: name 'title' is not defined
我现在处于这个阶段,想把所有的数据放入我的数据库中,但是我希望确保这段代码已经考虑到了当一个块缺少出版物位置行时应该怎么办,在这种情况下,只需在该行中留空该列。
以下是我编写的代码:
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
有人能告诉我为什么我的代码中明确定义了名称,但还是出现名称错误吗?!
line.startswith("#*")
是否真的为真吗?或许可以在这个代码块中加入一个打印语句来检查一下。 - Morgan Thrapp