给定一个csv文件,在不使用第三方库的前提下,按照列表的方式格式化输出该文件的内容,第一行是标题,第二行以下是数据,要求一一对应(面试的时候遇到的一道基础题)
打开文件:demo.csv
文件内容:
年,制造商,型号,说明,价格 1997,Ford,E350,"ac, abs, moon",3000.00 1999,Chevy,"Venture ""Extended Edition""","",4900.00 1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00 1996,Jeep,Grand Cherokee,"MUST SELL! air, moon roof, loaded",4799.00 2000,,"test 1",5000
输出:
['年', '制造商', '型号', '说明', '价格'] ['1997', 'Ford', 'E350', '"ac, abs, moon"', '3000.00'] ['1999', 'Chevy', '"Venture ""Extended Edition"""', '""', '4900.00'] ['1999', 'Chevy', '"Venture ""Extended Edition', ' Very Large"""', '""', '5000.00'] ['1996', 'Jeep', 'Grand Cherokee', '"MUST SELL! air, moon roof, loaded"', '4799.00'] ['2000', '', '"test 1"', '5000']
解题代码:
def func(li): ''' type: l: list rtype: st: string ''' #先把每一行的换行符删掉 if "n" in li: li.remove("n") #创建两个列表来保存引号的索引和逗号的索引 a = [] b = [] for i in range(len(li)): if li[i] == '"': a.append(i) if li[i] == ',': b.append(i) #遍历引号的值,两个一组和逗号索引进行比较,如果在引号中间,则把逗号变成“$“(这个值自己随便写,后续把字符串按照逗号分割后,再把$换成逗号) for i in range(0,len(a),2): for j in b: if a[i]可以直接保存到EXCEL中。