2013-12-18 9 views
0

코드 조각을 사용하여 다음 데이터와 함께 다음 오류가 발생합니다. 이걸 좀 도와 주실 래요? 저는 파이썬에서 초보자입니다. 데이터 :파이썬에서 csv 파일 읽기

"Id","Title","Body","Tags" 
"Id1","Tit,le1","Body1","Ta,gs1" 
"Id","Title","Body","Ta,2gs" 

코드 :

#!/usr/bin/python 
import csv,sys 
if len(sys.argv) <> 3: 
print >>sys.stderr, 'Wrong number of arguments. This tool will print first n records from a comma separated CSV file.' 
print >>sys.stderr, 'Usage:' 
print >>sys.stderr, '  python', sys.argv[0], '<file> <number-of-lines>' 
sys.exit(1) 

fileName = sys.argv[1] 
n = int(sys.argv[2]) 

i = 0 
out = csv.writer(sys.stdout, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC) 

ret = [] 


def read_csv(file_path, has_header = True): 
    with open(file_path) as f: 
     if has_header: f.readline() 
     data = [] 
     for line in f: 
      line = line.strip().split("\",\"") 
      data.append([x for x in line]) 
    return data 


ret = read_csv(fileName) 
target = [] 
train = [] 
target = [x[2] for x in ret] 
train = [x[1] for x in ret] 

오류 :

target = [x[2] for x in ret] 
IndexError: list index out of range 
+0

생성 된 파일이 두 줄 이상이없는? –

+0

죄송합니다. 데이터 오류. 나는 지금 질문을 편집했다. 고마워요 @PauloBu – novieq

+0

[x in line]에 대한 [x]의 요점은 무엇입니까? –

답변

3

당신은 file.readline()를 혼합하고 반복 가능한로 파일 객체를 사용하고 있습니다. 그러지 마. 대신 next()을 사용하십시오.

또한 데이터를 읽으려면 csv.reader() 모듈을 사용해야합니다.이 휠을 재발 명하지 마십시오. csv 모듈은 어떤 경우에 훨씬 더 thevalues에 포함 된 구분 기호와 CSV 값을 인용 처리 할 수 ​​

import csv 

def read_csv(file_path, has_header=True): 
    with open(file_path, 'rb') as f: 
     reader = csv.reader(f) 
     if has_header: next(reader, None) 
     return list(reader) 

마지막으로, 당신은 행과 열 전치 할 zip()를 사용할 수 있습니다 여기에

ret = read_csv(fileName) 
target, train = zip(*ret)[1:3] # just the 2nd and 3rd columns 

zip()을 첫 번째 행에서 이 아니고이 아닌 열에서 멈추고 적어도 예외를 피하십시오. 행의 일부에없는 열이있는 경우

(파이썬 3 itertools.zip_longest()) 대신 itertools.izip_longest()를 사용

from itertools import izip_longest 

ret = read_csv(fileName) 
target, train = izip_longest(*ret)[1:3] # just the 2nd and 3rd columns 

기본입니다 None에없는 열을 대체 할; 다른 값을 사용해야하는 경우, izip_longest()fillvalue 인수를 전달합니다

target, train = izip_longest(*ret, fillvalue=0)[1:3] # just the 2nd and 3rd columns 
+0

감사합니다. @Martijin. 다음 오류가 나타납니다. target, train = zip (* ret) [1 : 2] ValueError : 압축을 해제 할 값이 0 개 이상이어야합니다. – novieq

+0

@novieq :이 경우 CSV 파일이 비어 있습니다. 작업 할 컬럼이 없다면,'zip()'는 빈리스트를 반환했습니다. –

+0

인쇄 (ret [0] [2]) 인쇄 (ret [1] [2]) target, train = zip (* ret) [1 : 2]'및 출력을 볼 수 있습니다. 따라서 csv는 올바르게 구문 분석됩니다. @Martijn에게 미리 감사드립니다. – novieq