2016-09-04 2 views
0
import csv 

base='[email protected],username1\ 
[email protected],username2\ 
[email protected],username3\ 
[email protected],username4\ 
[email protected],username5' 

parsed=csv.reader(base, delimiter=',') 
for p in parsed: 
    print p 

반환 작동하지 않습니다CSV 구분 기호가 제대로 [파이썬]

['e'] 
['e'] 
['s'] 
['t'] 
['1'] 
['@'] 
['m'] 
['a'] 
['i'] 
['l'] 
['.'] 
['r'] 
['u'] 
['', ''] 

...

내가 데이터를 쉼표로 구분하여 얻을 수있는 방법

? 는 ('[email protected]은', '사용자 이름 1'), 는 ('[email protected]은', '사용자 이름 2'), 는 ... 내가 생각

답변

2

는 CSV는 개체와 같은 파일을 사용할 수 있습니다. 이 경우 StringIO를 사용할 수 있습니다.

import csv 
import StringIO 

base='''[email protected],username 
[email protected],username2 
[email protected],username3 
[email protected],username4 
[email protected],username5''' 

parsed=csv.reader(StringIO.StringIO(base), delimiter=',') 
for p in parsed: 
    print p 

OUTPUT은

['[email protected]', 'username'] 
['[email protected]', 'username2'] 
['[email protected]', 'username3'] 
['[email protected]', 'username4'] 
['[email protected]', 'username5'] 

또한, 귀하의 예를 들어 문자열은

['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'username5'] 

을 얻을 것입니다, 그래서 내가 그랬던 것처럼 당신은 '''을 사용할 수 있습니다, 뉴 라인, 또는처럼 base을 변경하지 않습니다

base='[email protected],username\n\ 
[email protected],username2\n\ 
[email protected],username3\n\ 
[email protected],username4\n\ 
[email protected],username5' 

EDIT
문서에 따르면, 인수는 파일과 유사한 개체 또는 목록 일 수 있습니다. 그래서이 너무 official docs on csv module (강조 광산)를 인용

parsed=csv.reader(base.splitlines(), delimiter=',') 
1

작동합니다

csv.reader(csvfile, dialect='excel', **fmtparams)

반환 주어진 csvfile의 행을 반복하는 리더 객체입니다. csvfile은 반복자 프로토콜을 지원하고 __next__() 메서드가 이라는 파일 이름과 목록 개체가 모두 적합 할 때마다 문자열을 반환 할 수 있습니다.

는 문자열 반복자를 지원하지만 하나, 여러 줄 문자열에서하지 선으로 문자열 하나에서 문자를 얻을 수 있습니다.

>>> s = "abcdef" 
>>> i = iter(s) 
>>> next(i) 
'a' 
>>> next(i) 
'b' 
>>> next(i) 
'c' 

그래서 작업은 라인 각 반복에하지 문자를 얻을 것이다 반복자를 만드는 것입니다. 불행히도 문자열 리터럴은 여러 줄 문자열이 아닙니다.

base = '[email protected],[email protected],[email protected],[email protected],[email protected],username5 

Esentially 올바르게 해당 문자열을 구문 분석하는 데 필요한 정보가 없습니다 :

base='[email protected],username1\ 
[email protected],username2\ 
[email protected],username3\ 
[email protected],username4\ 
[email protected],username5' 

은 동일합니다.당신이 개행 문자로 당신의 문자열을 분할 할 수 있습니다이 변경 후

base='''[email protected],username1 
[email protected],username2 
[email protected],username3 
[email protected],username4 
[email protected],username5''' 

을하고 모든 것이 잘 작동합니다 : 문자 대신 여러 문자열을 사용하십시오

parsed=csv.reader(base.splitlines(), delimiter=',') 
for p in parsed: 
    print(p) 
관련 문제