2015-01-07 2 views
0

이 스크립트는 CSV 파일에서 목록을 구문 분석하고 정렬하여 머리글을 포함하여 새로 만든 csv 파일에 저장합니다.python 및 csv 모듈에서 CSV 파일 구문 분석 및 저장

필자는이 파서의 출력을 다음과 함께 새 CSV 파일에 저장하는 쓰기 기능을 포함합니다. 이 코드는 csv를 만들지 만 헤더는 하나의 열에 만 기록합니다. 여기

Timestamp,Session Index,Event,Description,Version,Platform,Device,User ID,Params, 
"Dec 27, 2014 05:26 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,{}, 
"Dec 27, 2014 05:24 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,{}, 
"Dec 27, 2014 05:23 AM",1,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),,{ UserID : 54807; tabName : Home}, 
"Dec 27, 2014 05:23 AM",2,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),,{ UserID : 54807; tabName : Home}, 
"Dec 27, 2014 05:23 AM",3,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),,{ UserID : 54807; tabName : QuickAndEasy}, 

내가 원하는 출력이 CSV로 저장하려면 것 : 여기

입력의

Timestamp,Session Index,Event,Description,Version,Platform,Device,User ID,TabName,RecipeID,Type,SearchWord,IsFromLabel, 
"Dec 27, 2014 05:26 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,,,,,, 
"Dec 27, 2014 05:24 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,,,,,, 
"Dec 27, 2014 05:23 AM",1,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),54807,Home,,,,, 
"Dec 27, 2014 05:23 AM",2,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),54807,Home,,,,, 
"Dec 27, 2014 05:23 AM",3,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),54807,QuickAndEasy,,,,, 

코드 :

import csv 


def printfields(keys, linesets): 
    output_line = "" 
    for key in keys: 
     if key in linesets: 
      output_line += linesets[key] + "," 
     else: 
      output_line += "," 
    print output_line 


def csvwriter(reader, path): 
    """ 
    write reader to a csv file path 
    """ 
    with open(path, "w") as csv_file: 
     writer = csv.writer(csv_file, delimiter=",") 
     for line1 in line: 
      if line1 in path: 
       writer.writerow(line1) 

if __name__ == "__main__": 
    fields = [ 
     "UserID", "tabName", "RecipeID", "type", "searchWord", "isFromLabel", "targetUID" 
    ] 
    mappedLines = {} 
    with open('test.csv', 'r') as f: 
     reader = csv.DictReader(f) 
     for line in reader: 
      fieldPairs = [ 
       p for p in 
       line['Params'].strip().strip('}').strip('{').strip().split(';') 
       if p 
      ] 
      lineDict = { 
       pair.split()[0].strip(): pair.split(':')[1].strip() 
       for pair in fieldPairs 
      } 
      mappedLines[reader.line_num] = lineDict 
     path = "output.csv" 
     csvwriter(reader, path) 

    for key in sorted(mappedLines.keys()): 
     linesets = mappedLines[key] 
     printfields(fields, linesets) 
+0

귀하의 들여 쓰기를 매핑

def csv_writer(lines, path): """ write reader to a csv file path """ with open(path, "w") as csv_file: writer = csv.DictWriter(csv_file, fields) writer.writeheader() # Iterate over dict for line1, val in lines.iteritems(): writer.writerow(val) 

사용이 잘못되었습니다. 'def' 명령 뒤에 들여 쓰기를 추가해야합니다. https://docs.python.org/2/tutorial/controlflow.html#defining-functions – shevski

+0

고마워, 이제 이것이 적절하게 들여 쓰기가되었다고 생각합니다. – mmarboeuf

+0

샘플 입력? 원하는 출력 예? –

답변

0

당신은 당신의 코드에서 몇 가지 문제를 가지고

먼저 dict를 작성하는 파일

fields = [ 
    "Timestamp","Session Index","Event","Description","Version","Platform","Device","User ID","Params","" 
] 

사용 DictWriter의 상단이 걸릴. 당신이

 csv_writer(mappedLines, path) 
+0

고마워요! 큰 도움. 그러나 나는 아직도 새로 만든 csv에 처음 8 열을 써야합니다. 그걸 어떻게하는지 모르겠다. – mmarboeuf

0

csv_writer 참조 상징 line - 이것은 함수에 대한 인수가 아닙니다. 그게 어떻게 제공되기를 기대합니까?

+0

어떻게 제공 될 것으로 예상됩니까? 죄송합니다. 무슨 뜻인지 잘 모르겠습니다. 함수 이름에 밑줄을 다시 표시했습니다. – mmarboeuf