2017-02-01 1 views
0

이미 개발 한 알고리즘을 최적화하는 방법을 찾고 있습니다. 내 질문의 제목을 말했듯이, 나는 쉼표로 구분 된 문자열을 처리하는 경우가 있는데, 그 중에는 쉼표가 포함될 수도 있습니다. 이것은 큰 데이터의 맥락에서 모두 이루어 지므로 속도가 중요합니다. 내가 여기있는 것은 내가 필요로하는 모든 일을하지만, 나는 그것을하는 더 빠른 방법이있을 것이라고 믿어야 만한다. 당신이 어떤 제안이라도 듣고 싶습니다. 미리 감사드립니다.Python을 사용하여 쉼표로 구분 된 문자열을 쉼표로 파싱

코드 :

import os,re 


commaProblemA=re.compile('^"[\s\w\-()/*[email protected]!#%^\'&$\{\}|<>:0-9]+$') 

commaProblemB=re.compile('^[\s\w\-()/*[email protected]!#%^\'&$\{\}|<>:0-9]*"$') 

#example string 
#these are read from a file in practice 
z=',,"N/A","DWIGHT\'s BEET FARM,INC.","CAMUS,ALBERT",35.00,0.00,"NIETZSCHE,FRIEDRICH","God, I hope this works, fast.",,,35.00,,,"",,,,,,,,,,,"20,4,2,3,2,33","223,2,3,,34 00:00:00:000000",,,,,,,,,,,,0,,,,,,"ERW-400",,,,,,,,,,,,,,,1,,,,,,,"BLA",,"IGE6560",,,,' 

testList=z.split(',') 


for i in testList: 
    if re.match(commaProblemA,i): 
     startingIndex=testList.index(i) 
     endingIndex=testList.index(i) 
     count=0 
     while True: 
      endingIndex+=1 
      if re.match(commaProblemB,testList[endingIndex]): 
       diff=endingIndex-startingIndex 
       while count<diff:    
        testList[startingIndex]=(testList[startingIndex]+","+testList[startingIndex+1]) 
        testList.pop(startingIndex+1) 
        count+=1     
       break 




print(str(lineList)) 
print(len(lineList)) 
+3

바퀴를 재 활성화 하시겠습니까? https://docs.python.org/2/library/csv.html – e4c5

+1

[StringIO] (https://docs.python.org/3/library/io.html#io.StringIO)와 [ CSV 모듈] (https://docs.python.org/3/library/csv.html#csv.reader). 문자열 스트림을 읽을 때'quotechar' 매개 변수를 사용해야합니다. – Abdou

+0

예, 저는 바퀴를 재발견하고 싶습니다. 그것은 내가 생각하는 것들이 어떻게 작용 하는지를 진정으로 이해하는 좋은 방법입니다. 또한, 가치가있는 것 (그다지)이 아니라면, 내 방식이 멋지다고 생각합니다. –

답변

1

당신이 정말이 자신을 대신 라이브러리를 사용하여 작업을 수행하려면 먼저 몇 가지 팁 :

  • 는 CSV 데이터에 split()를 사용하지 않습니다. (성능에 좋지 않음) 성능을 위해
  • : regEx를 사용하지 마십시오. (한 줄 CSV 가정 의사 코드를)

같은 것 데이터를 스캔 할 정규 방법 : 더 나은 성능을 위해

for each line 
    bool insideQuotes = false; 
    while not end of line { 

     if currentChar == '"' 
      insideQuotes = !insideQuotes; // (! meaning 'not') 
      // this also handles the case of escaped quotes inside the field 
      // (if escaped with an extra quote) 

     else if currentChar == ',' and !insideQuotes 
      // seperator found - handle field 
    } 

을 당신은 바이너리 모드로 파일을 열고 줄 바꿈을 처리 할 수 자신을 스캔하는 동안. 이렇게하면 줄을 스캔하거나 버퍼에서 복사 (예 : getline() 또는 유사한 기능 사용) 한 다음 해당 버퍼를 다시 스캔하여 필드를 추출 할 필요가 없습니다.

관련 문제