2014-04-24 4 views
2

다음 형식의 데이터가 포함 된 텍스트 파일이 있습니다.여러 줄 텍스트 파일을 여러 줄로 된 CSV 파일로 분할

100157 100157 
100157 364207 
100157 38848 
100157 bradshaw97introduction 
100157 bylund99coordinating 
100157 dix01metaagent 
100157 gray99finding 
... 
... 

나는 다음과 같은 방법을 사용하여 scikit 읽을 수있는 데이터 세트에이 변환하려고 해요 :

내가하려는 반면
datafile = open(filename.txt, 'r') 
data=[] 
for row in datafile: 
    data.append(row.strip().split('\t')) 

c1 = open(filename.csv, 'w') 
arr = str(data) 
c.write(arr) 
c.close 

그러나이 코드를 실행 한 후, 데이터는 단일 행에 출력됩니다 아이리스 데이터 세트와 같은 행과 열에서 깔끔하게 CSV 형식으로 분리 된 데이터를 얻으십시오.

진행 방법에 대한 도움을 얻을 수 있습니까? 감사.

+0

이 우리에게 보여주십시오

쉽게 공간으로 그것을 켤 수 있습니다 새로운 라인으로 구분 된 값을 분리. –

답변

0

저를 수정,하지만 난 scikit readable dataset\n이 행을 분리하여 단지 공간이 구분 된 값이라고 생각?

때문에, 아주 쉽게 경우 탭으로 구분

100157 100157 
100157 364207 
100157 38848 
100157 bradshaw97introduction 
100157 bylund99coordinating 
100157 dix01metaagent 
100157 gray99finding 

:

가이 파일을 가정합니다. 결과는 같이 방법을

with open('/tmp/test.csv', 'r') as fin, open('/tmp/test.out', 'w') as fout: 
    data=[row.strip().split('\t') for row in fin] 
    st='\n'.join(' '.join(e) for e in data) 
    fout.write(st) 

print data 
# [['100157', '100157'], ['100157', '364207'], ['100157', '38848'], ['100157', 'bradshaw97introduction'], ['100157', 'bylund99coordinating'], ['100157', 'dix01metaagent'], ['100157', 'gray99finding']] 
print st 
100157 100157 
100157 364207 
100157 38848 
100157 bradshaw97introduction 
100157 bylund99coordinating 
100157 dix01metaagent 
100157 gray99finding 
+0

코드가 잘 작동했습니다. 감사! – user3466132

2

사용 csv module :

import csv 

with open('filename.txt', 'r') as f, open('filename.csv', 'w') as fout: 
    writer = csv.writer(fout) 
    writer.writerows(line.rstrip().split('\t') for line in f) 

출력 csv 파일 : 나는 틀렸다면

100157,100157 
100157,364207 
100157,38848 
100157,bradshaw97introduction 
100157,bylund99coordinating 
100157,dix01metaagent 
100157,gray99finding 
... 
+0

그것은 빠르다 !! 고마워. – user3466132

+0

@ user3466132, 스택 오버플로에 오신 것을 환영합니다! 귀하의 질문에 답변을 시도한 사람들이 있습니다. 이것이 도움이된다면, 당신에게 가장 유용한 [답변 수락] (http://meta.stackexchange.com/a/5235)으로 커뮤니티에 알릴 수 있습니다. – falsetru

+0

@falsetru는'line.split()'충분하지 않습니까? – cdhagmann

관련 문제