gpt4 book ai didi

python - 如何将包含引号的 csv 字段拆分为两个字段?

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:30 26 4
gpt4 key购买 nike

最终编辑:有效!感谢大家的帮助,特别感谢 Padraic 在我开始工作之前帮助我。

首先,如果之前有人问过这个问题,我深表歉意,我确实进行了相当广泛的搜索,但也许它的措辞方式出乎我的意料。

所以我正在处理一个像这样的 csv 文件:

0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5,21171,7.25,S

我必须解析这个文件,然后将它的一部分写入我用这段代码完成的另一个 csv:

import csv
infile = open('data/data.csv', 'r')
incsv = csv.reader(infile, delimiter = ',')
outfile = open('data/output.csv', 'w', newline = '')
outcsv = csv.writer(outfile, delimiter = ',')

问题是“名称”字段的格式为 "Lastname, othernames",我需要将其拆分为两个字段:“lastname”和“othernames”。

我似乎无法找到一种方法让它忽略引号并用定界符 (',') 分隔名称。这是一个列表,所以 .strip() 不起作用,而且我无法弄清楚 quote_none 是否不起作用,或者我只是没有语法。

这可能不言而喻,但我对这一切都很陌生。

编辑:我在使用这些解决方案时遇到了错误,因此我将包含其余代码,希望它能突出显示出错的地方。

import csv

infile = open('data/titanic.csv', 'r')
incsv = csv.reader(infile, delimiter = ',')
outfile = open('data/survivors.csv', 'w', newline = '')
outcsv = csv.writer(outfile, delimiter = ',')

dict ={}

for row in incsv:
survived, pclass, name, sex, age, sibsp, parch, ticket, fare, cabin, embarked = row
if survived == "1":
if name not in dict:
dict[name] = name, pclass, sex, age

names = dict.keys()
sorted_names = sorted(names)

for name in sorted_names:
(name, pclass, sex, age) = dict[name]
rowOutput = (name, pclass, sex, age)
outcsv.writerow(rowOutput)

outfile.close()
infile.close()

所以这会解析原始 csv,通过 survived == '1' 进行过滤,将名称添加到字典中(我知道一旦拆分名称字段我将需要调整它),然后按字母顺序对该字典进行排序。

编辑:这是按要求提供的更多原始文件。很抱歉最初没有包含更多内容。

survived,pclass,name,sex,age,sibsp,parch,ticket,fare,cabin,embarked
0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S
1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C
1,3,"Heikkinen, Miss. Laina",female,26,0,0,STON/O2. 3101282,7.925,,S
1,1,"Futrelle, Mrs. Jacques Heath (Lily May Peel)",female,35,1,0,113803,53.1,C123,S
0,3,"Allen, Mr. William Henry",male,35,0,0,373450,8.05,,S
0,3,"Moran, Mr. James",male,,0,0,330877,8.4583,,Q
0,1,"McCarthy, Mr. Timothy J",male,54,0,0,17463,51.8625,E46,S
0,3,"Palsson, Master. Gosta Leonard",male,2,3,1,349909,21.075,,S
1,3,"Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)",female,27,0,2,347742,11.1333,,S

这是 892 行的 10 行(如果不计算标题,则为 891)。

最佳答案

您可以在遍历时修改列表:

for row in incsv:
row[2:2] = row[2].split(',')
outcsv.writerow(row)

关于python - 如何将包含引号的 csv 字段拆分为两个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37321627/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com