我有一个不一致的csv文件。看起来像这样,其中有些具有中间名,有些则没有。我不知道解决此问题的最佳方法。中间名称(如果存在)将始终位于第二位置。但是,如果中间名不存在,则姓氏排在第二位。
john,doe,52,florida
jane,mary,doe,55,texas
fred,johnson,23,maine
wally,mark,david,44,florida
答案 0 :(得分:1)
假设您拥有①wrong.csv
,并且想产生②fixed.csv
。
您要从①中读取一行,对其进行修复,然后将固定的行写入②,可以这样完成
with open('wrong.csv') as input, open('fixed.csv', 'w') as output:
for line in input:
line = fix(line)
output.write(line)
现在我们要定义fix
函数...
每行有3或4个字段,以逗号分隔,所以我们要做的是使用逗号作为分隔符来分割行,如果字段数为3,则返回未修改的行,否则将字段0联接起来字段1(Python从零开始计数...),重新组装输出行并将其返回给调用方。
def fix(line):
items = line.split(',') # items is a list of strings
if len(items) == 3: # the line is OK as it stands
return line
# join first and middle name
first_middle = join(' ')((items[0], items[1]))
# we want to return a "fixed" line,
# i.e., a string not a list of strings
# we have to join the new name with the remaining info
return ','.join([first_second]+items[2:])