【问题标题】:Python - Write a new row for each list data under same header into csvPython - 将同一标题下的每个列表数据的新行写入csv
【发布时间】:2021-11-29 12:41:24
【问题描述】:

我有一个文本文件“student.txt”。有些键有多个值。我只想要与名称相关的数据,以及该名称下方的兄弟和爱好值。

'student.txt'

ignore me
name-> Alice
name-> Sam
sibling-> Kate,
unwanted
sibling-> Luke,
hobby_1-> football
hobby_2-> games
name-> Ramsay
hobby_1-> dance
unwanted data
hobby_2-> swimming
hobby_3-> jogging
ignore data

我已经完成的代码:

file = open("student.txt", "r")


with open("student.csv", "w") as writer:
    main_dict = {}
    student_dict = {"Siblings": "N/A", "Hobbies": "N/A"}
    sibling_list = []
    hobby_list = []
    flag = True
    writer.write ('name,siblings,hobbies\n')
    header = 'Name,Siblings,Hobbies'.split(',')

    sib_str = ''
    hob_str =''

    for eachline in file:
        try:
            key, value = eachline.split("-> ")
            value = value.strip(",\n")
            if flag:
                    if key == "name":
                        print (key,value)
                        if len(sibling_list) > 0:
                            main_dict[name]["Siblings"] = sib_str
                            #print (main_dict)
                        if len(hobby_list) > 0:
                            main_dict[name]["Hobbies"] = hob_str
                        sibling_list = []
                        hobby_list = []
                        name = value
                        main_dict[name] = student_dict.copy()
                        main_dict[name]["Name"] = name

                    elif key == "sibling":
                        sibling_list.append(value)
                        sib_str= ' '.join(sibling_list).replace(' ', '\n')
                        

                    elif key.startswith("hobby"):
                        hobby_list.append(value)
                        hob_str = ' '.join(hobby_list)


                    if len(sibling_list) > 0:
                        main_dict[name]["Siblings"] = sib_str
                    if len(hobby_list) > 0:
                        main_dict[name]["Hobbies"] = hob_str

            if 'name' in eachline:
                if 'name' in eachline:
                    flag = True
                else:
                    flag = False

        except:
            pass

    
    for eachname in main_dict.keys():
        for eachkey in header:
            writer.write(str(main_dict[eachname][eachkey]))
            writer.write (',')

            if 'Hobbies' in eachkey:
                writer.write ('\n')

上述代码的 CSV 输出:

预期的 CSV 输出:

P.S:我似乎无法弄清楚如何不放弃尝试/通过。因为有些行(没有'->')是不需要的,我不能使用 eachline.split("->")。也希望能提供帮助。

非常感谢!

【问题讨论】:

  • 为什么不能使用eachline.split("-> ")

标签: python list csv dictionary


【解决方案1】:

下面的代码给出了 csv 文件,您可以将其导入 Excel 中,它的格式与您期望的完全相同。

你可以使用类似的东西

if "->" not in line:
    continue

要跳过不包含“->”值的行,请参见下面的代码:

import csv

file = open("student.txt", "r")

students = {}
name = ""
for line in file:
    if "->" not in line:
        continue
    line = line.strip(",\n")
    line = line.replace(" ", "")
    key, value = line.split("->")
    if key == "name":
        name = value
        students[name] = {}
        students[name]["siblings"] = []
        students[name]["hobbies"] = []
    else:
        if "sibling" in key:
            students[name]["siblings"].append(value)
        elif "hobby" in key:
            students[name]["hobbies"].append(value)

#print(students)

csvlines = []
for student in students:
    name = student
    hobbies = students[name]["hobbies"]
    siblings = students[name]["siblings"]
    maxlength = 0
    if len(hobbies) > len(siblings) :
        maxlength = len(hobbies)
    else:
        maxlength = len(siblings)
    if maxlength == 0:
        csvlines.append([name, "N/A", "N/A"])
        continue
    for i in range(maxlength):
        if i < len(siblings):
            siblingvalue = siblings[i]
        elif i == len(siblings):
            siblingvalue = "N/A"
        else:
            siblingvalue = ""

        if i < len(hobbies):
            hobbyvalue = hobbies[i]
        elif i == len(siblings):
            hobbyvalue = "N/A"
        else:
            hobbyvalue = ""

        if i == 0:
            csvlines.append([name, siblingvalue, hobbyvalue])
        else:
            csvlines.append(["", siblingvalue, hobbyvalue])

print(csvlines)
fields = ["name", "siblings", "hobbies"]

with open("students.csv", 'w') as csvfile:
    # creating a csv writer object
    csvwriter = csv.writer(csvfile)

    # writing the fields
    csvwriter.writerow(fields)

    # writing the data rows
    csvwriter.writerows(csvlines)

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 2019-03-02
    • 2019-02-14
    • 2018-05-15
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2012-12-17
    相关资源
    最近更新 更多