:( scourgify.py 清理短的 CSV 文件 || :| scourgify.py 清理长的 CSV 文件

huangapple go评论145阅读模式
英文:

:( scourgify.py 清理短的 CSV 文件 || :| scourgify.py 清理长的 CSV 文件 scourgify.py cleans short CSV file || :( scourgify.py 清理短的 CSV 文件 || :| scourgify.py 清理长的 CSV 文件 scourgify.py cleans long CSV file

问题

我正在尝试解决CS50的scourgify问题。在名为before.csv的文件中,有两列分别是name和house。任务是将name列拆分为两个独立的列,即first和last。然后创建一个新文件,并将这些信息写入其中:first、last和house。我几乎通过了所有的测试用例,但我不知道为什么会收到这些错误消息,即使我的程序给出了预期的结果。

:( scourgify.py清理短的CSV文件
原因
scourgify.py没有生成指定格式的CSV文件
日志
运行python3 scourgify.py before.csv after.csv...
检查程序是否以状态0退出...
检查after.csv是否存在...
:| scourgify.py清理长的CSV文件
原因
在笑容变成颠倒之前无法检查

这是我整体的代码实现:

import sys
import csv


def main():
    if len(sys.argv) >= 4:
        print("命令行参数过多")
        sys.exit(1)

    if len(sys.argv) <= 2:
        print("命令行参数过少")
        sys.exit(1)

    filepath1 = sys.argv[1]
    filepath2 = sys.argv[2]
    if not filepath1.endswith(".csv") or not filepath2.endswith(".csv"):
        print("不是CSV文件")
        sys.exit(1)

    data = read_from_file(filepath1)
    writer = write_to_file(filepath2, data)

def read_from_file(filepath):
    updated_data = []
    try:
        with open(filepath, "r") as file:
            data = csv.DictReader(file)

            for i in data:
                name = i["name"]
                house = i["house"]
                first, last = name.split(", ")
                new_dict = {
                    "first": first,
                    "last": last,
                    "house": house,
                }
                updated_data.append(new_dict)

    except FileNotFoundError:
        print("文件不存在")
        sys.exit(1)

    return updated_data


def write_to_file(filepath, new_data):
    fieldnames = ["first", "last", "house"]
    try:
        with open(filepath, mode="w") as file:
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(new_data)

    except FileNotFoundError:
        print("文件不存在")
        sys.exit(1)


if __name__ == "__main__":
    main()

我查看了一些与这个问题集相关的问题,但它们没有帮助。如果有人知道问题所在,我将非常感谢听到您的意见。

英文:

I am trying to solve CS50's scourgify problem. In the file called before.csv there are two columns name, house respectively. The task is to split name column into two independent columns namely first and last. After then create new file and write this information: first, last, house. I almost past all the test cases, but I do not have a clue why am I getting this error messages even my program gives me expected result.

:( scourgify.py cleans short CSV file
Cause
scourgify.py does not produce CSV with specified format
Log
running python3 scourgify.py before.csv after.csv...
checking that program exited with status 0...
checking that after.csv exists...
:| scourgify.py cleans long CSV file
Cause
can&#39;t check until a frown turns upside down

Here is my overall code implementation:

import sys
import csv


def main():
    if len(sys.argv) &gt;= 4:
        print(&quot;Too many command-line arguments&quot;)
        sys.exit(1)

    if len(sys.argv) &lt;= 2:
        print(&quot;Too few command-line arguments&quot;)
        sys.exit(1)

    filepath1 = sys.argv[1]
    filepath2 = sys.argv[2]
    if not filepath1.endswith(&quot;.csv&quot;) or not filepath2.endswith(&quot;.csv&quot;):
        print(&quot;Not a CSV file&quot;)
        sys.exit(1)

    data = read_from_file(filepath1)
    writer = write_to_file(filepath2, data)

def read_from_file(filepath):
    updated_data = []
    try:
        with open(filepath, &quot;r&quot;) as file:
            data = csv.DictReader(file)

            for i in data:
                name = i[&quot;name&quot;]
                house = i[&quot;house&quot;]
                first, last = name.split(&quot;, &quot;)
                new_dict = {
                    &quot;first&quot;: first,
                    &quot;last&quot;: last,
                    &quot;house&quot;: house,
                }
                updated_data.append(new_dict)

    except FileNotFoundError:
        print(&quot;File does not exist&quot;)
        sys.exit(1)

    return updated_data


def write_to_file(filepath, new_data):
    fieldnames = [&quot;first&quot;, &quot;last&quot;, &quot;house&quot;]
    try:
        with open(filepath, mode=&quot;w&quot;) as file:
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(new_data)

    except FileNotFoundError:
        print(&quot;File does not exist&quot;)
        sys.exit(1)


if __name__ == &quot;__main__&quot;:
    main()

I checked some questions relating to this problem set, but they were not helpful. If anybody knows what is the problem, I would be grateful to hear from you.

答案1

得分: 2

我发现了我的错误:

for i in data:
    name = i["name"]
    house = i["house"]
    last, first = name.split(", ")
    new_dict = {
        "first": first,
        "last": last,
        "house": house,
    }
    updated_data.append(new_dict)

当我遍历每一行时,我犯了一个错误,即将last, first = name.split(", ")写成了first, last = name.split(", ")。要小心这样的简单错误,因为我花了一些时间才找到它。

英文:

I found my bug:

            for i in data:
            name = i[&quot;name&quot;]
            house = i[&quot;house&quot;]
            last, first = name.split(&quot;, &quot;)
            new_dict = {
                &quot;first&quot;: first,
                &quot;last&quot;: last,
                &quot;house&quot;: house,
            }
            updated_data.append(new_dict)

When I am looping through each row I made me mistake which is instead of assigning last, first = name.split(&quot;, &quot;), I did first, last = name.split(&quot;, &quot;). Be careful like this simple errors because it took me sometime to find it.

huangapple
  • 本文由 发表于 2023年8月9日 15:34:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865547.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定