诚然,此文件上的代码很丑陋,但它仍然可以正常工作,并已完成概述的任务。但是,检查程序发现错误。我将包括指向该链接。我的代码如下。关于为什么他们认为输出为空白的想法太棒了!
通过检查器:
"Expected Output:
[{'first': 'Luna', 'middle': None, 'last': 'Lovegood', 'house': 'Ravenclaw', 'birth': 1981}]
Actual Output:
[]"
https://submit.cs50.io/check50/10dd5ef79130cbd984475a9eaac72a8c3cf8f027
import sys
from sys import argv
from cs50 import SQL
import csv
# obtain file input
if len(sys.argv) != 2:
print("Enter one CSV file")
sys.exit(1)
# read file into reader
wizards = open(argv[1])
reader = csv.reader(wizards)
# create empty lists
fullnames = []
houses = []
yob = []
namecount = 0
# save name, houses and years from each row
for row in reader:
if namecount > 0:
fullnames.append(row[0])
houses.append(row[1])
yob.append(row[2])
namecount += 1
# create empty lists
firstnames = []
middlenames = []
lastnames = []
# seperate names. couldve used .split() to do all this in hindsight
for x in range(namecount - 1):
namelen = len(fullnames[x])
tname = fullnames[x]
spaces = 0
# finds spaces in names using length
for y in range(namelen - 1):
if tname[y] == " ":
spaces += 1
nchars = 0
# loops based on spaces and puts together names before and after spaces to save in respective name lists
for s in range(spaces + 1):
tempsn = tname[nchars]
# adds chars to name until space, comma or end of full name reached
while tname[nchars] != " " and tname != "," and nchars < namelen - 1:
nchars += 1
tempsn += tname[nchars]
# saves temp names into lists
if s == 0:
firstnames.append(tempsn)
elif s == 1 and spaces == 1:
middlenames.append(None)
lastnames.append(tempsn)
elif s == 1 and spaces == 2:
middlenames.append(tempsn)
else:
lastnames.append(tempsn)
nchars += 1
# opens sql database
db = SQL("sqlite:///students.db")
# for each name, puts associated data into table using SQL query
for h in range(namecount - 1):
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?)",
firstnames[h], middlenames[h], lastnames[h], houses[h], yob[h])
答案 0 :(得分:0)
让我们加入我们的循环已经在进行中。我们在“哈利”中的“ y”上:
while tname[nchars] != " " and tname != "," and nchars < namelen - 1:
nchars += 1
tempsn += tname[nchars]
它将空格添加到tempsn
。
您应该听您说:“ #个单独的名称。本来可以使用.split()事后查看”