【问题标题】:Using SQL and Python (CS50 PSET7)使用 SQL 和 Python (CS50 PSET7)
【发布时间】:2020-09-14 07:55:21
【问题描述】:

这个程序有两个部分。

  1. 在 import.py 中,编写从 CSV 电子表格导入数据的程序。 CSV 电子表格包含全名、出生、年份,我想将全名分隔为“名字”、“中间名”、“姓氏”。我的程序如下:

import.py

from csv import reader
from sys import argv, exit
from cs50 import SQL
import csv
import sys

# check command line arguments
if len(sys.argv) != 2:
    print(f"Usage: import.py .csv")
    exit(1)

if not argv[1].endswith(".csv"):
    print(f"Usage: import.py .csv 3 arg")
    exit(1)

# variables
db = SQL("sqlite:///students.db")

total = 0
first = []
middle = []
last = []
house = []
birth = []

with open(argv[1], 'r') as csvfile:
    data = csv.reader(csvfile)

    for row in data:
        names = row[0]
        house = row[1]
        birth = row[2]
    total = total + 1

# split names

    if len(names) == 2:
        first.append(names[0])
        middle.append('None')
        last.append(names[1])

    if len(names) == 3:
        first.append(names[0])
        middle.append(middle[2])
        last.append(names[2])

    for i in range(total - 1):
        db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?)", first[i], middle[i], last[i], house[i], birth[i])
  1. 第二部分 roster.py 的任务是编写一个程序,该程序按字母顺序打印给定房子的学生列表。

例如对于

$ python roster.py Gryffindor

程序应该返回例如

Hermione Jean Granger, born 1979
Harry James Potter, born 1980
Ginevra Molly Weasley, born 1981
Ronald Bilius Weasley, born 1980

我的代码如下:

roster.py

from csv import reader
from sys import argv, exit
from cs50 import SQL
import sys

db = SQL("sqlite:///students.db")

# check command line arguments
if len(sys.argv) != 2:
    print(f"Usage: python roster.py house")
    exit(1)

house = sys.argv[1]

# if sys.argv[1].lower() != "slytherin" or sys.argv[1].lower() != "gryffindor" or sys.argv[1].lower() != "ravenclaw" or sys.argv[1].lower() != "hufflepuff":
  #  print("choose a house!")
   # exit(1)

rows = db.execute('SELECT * FROM students WHERE house = (?) ORDER BY last, first', sys.argv[1])

for row in rows:
    print(row['first'],end=" ")

    if row["middle"] != 'None':
        print(row['middle'],end=" ")

    print(row['last'],end=", ")
    print("born ", row['birth'])

我被困了很长时间,不明白为什么代码没有打印出名称!非常感谢您的帮助!

【问题讨论】:

    标签: python sql database sqlite cs50


    【解决方案1】:

    import.py 存在三个问题, 首先total 的缩进错误, 其次,您没有附加到列表,而是覆盖它, 最后,您的 create 语句不正确。

    看看这是否有帮助 -

    total = 0
    first = []
    middle = []
    last = []
    house = []
    birth = []
    
    with open(argv[1], 'r') as csvfile:
        data = csv.reader(csvfile)
    
        for row in data:
            names = row[0].split()
            house = row[1]
            birth = row[2]
            total = total + 1
    
            # split names
    
            if len(names) == 2:
                first.append(names[0])
                middle.append('None')
                last.append(names[1])
            
            if len(names) == 3:
                first.append(names[0])
                    middle .append(names[1])
                    last.append(names[2])
    
    db.execute("CREATE TABLE students (first char(100), middle char(100), last char(100), house char(100), birth char(100))")
    
    for i in range(total):
            db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?)", first[i], middle[i], last[i], house[i], birth[i])
    

    如您所见,我已将 CREATE 和 INSERT 分开。由于我不知道出生的数据类型,我假设它是 CHAR,请根据您的需要进行修改。

    【讨论】:

    • 非常感谢您的帮助!我不再收到错误,但在我运行 python roster.py hufflepuff 或任何房屋后没有打印出来。非常感谢任何建议!
    • 您的 CREATE 语句不正确,请参阅我在答案中编辑了最后几行代码。
    • 谢谢,但是,当我运行“python roster.py Slytherin”或任何房屋时,我仍然无法检索任何名称。
    • 请在打开csv前声明house=[]和birth=[],同时调用第二个脚本时请尽量输入与csv文件中相同大小写的house name。
    • 谢谢,好的,在打开 csv 之前添加了 house = [] 和birth = []。当我运行“python roster.py Slytherin”时仍然没有输出。不确定 roster.py 中是否有错误?我还更新了上面的代码。
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多