2016-10-17 7 views
-1

여러 텍스트 파일에서 데이터를 가져 와서 처리하는 방법에 대한 권장 사항 (예 : 합계 계산). 저는 파이썬에서 그렇게하려고 노력했지만 막 다른 길을 계속 지켜 왔습니다.여러 텍스트 파일의 데이터 처리

기계는 조작 할 때마다 텍스트 형식의 요약 파일을 생성합니다.이 예제에서는 배치에서 좋은 사과를 스크리닝합니다. 먼저 사과를 적재하고, 그 다음에 좋은 것을 나쁜 것과 분리 한 다음 나쁜 사과를 다시 적재하여 재검사하고 일부는 회복됩니다. 따라서 적어도 2 개의 요약 파일이 배치마다 생성됩니다. 이는 얼마나 많은 시간 동안 사과를로드하여 양호한 상태로 복구 할 수 있는지에 따라 달라집니다.

파일 1 :

general Info: 
    Batch No.  : A2J3 
    Operation  : Test 
    Fruit   : Apple 
    Operation Number : A5500 
    Quantity In  : 10 
yield info: 
    S1 S2  Total Bin Name 
    5 2  7  good 
    1 2  3  bad 

파일 2 :

텍스트 파일의 예입니다

general Info: 
    Batch No.  : A2J3 
    Operation  : Test 
    Fruit   : Apple 
    Operation Number : A5500 
    Quantity In  : 3 
yield info: 
    S1 S2  Total Bin Name 
    1 1  2  good 
    0 0  1  bad 

내가이 TXT 파일의 전체 폴더의 데이터를 얻을 싶어 테스트 결과를 다음 기준과 병합하십시오.

  1. 같은 배치 번호, 동일한 작업 (파일 이름이 아닌 txt 파일의 내용을 기반으로 함)에서 가져온 txt 파일을 식별하여 동일한 배치를 처리합니다.

  2. 2 개 이상의 요약 파일 데이터를 다음과 병합하십시오 형식 CSV :

    Lot: 
    Operation: 
    Bin  First Pass Second Pass Final Yield %Yield 
    Good  7   2   9   90% 
    Bad  3   1   1   10% 
    

S1, S2는 14에 1에서 갈 수 있지만, 결코 1 미만 우편함도 좋은 제한뿐만 아니라 (다른 텍스트 파일에 여러 종류를 가질 수, 변수 나쁜. 하지만 항상 나는 단지 아무것도, 아주 기본을 모르는,

Bins: 
Good 
Semi-bad 
Bad 
Worst 
... 

내가 파이썬에 새로 온 사람과 난 단지 학교에서이 스크립트 언어를 사용) 만 한 좋은 빈있을 것입니다. 배치 번호

with open('R0.txt') as fh_d10SunFile: 
    fh_d10SumFile_perline = fh_d10SunFile.read().splitlines() 
    #print fh_d10SumFile_perline 

TestProgramName_str = fh_d10SumFile_perline[CONST.TestProgram_field].split(':')[1] 
LotNumber_str  = fh_d10SumFile_perline[CONST.LotNumber_field].split(':')[1] 
QtyIn_int   = int(fh_d10SumFile_perline[CONST.UnitsIn_field].split(':')[1]) 
TestIteration_str = fh_d10SumFile_perline[CONST.TestIteration_field].split(':')[1] 
TestType_str  = fh_d10SumFile_perline[CONST.TestType_field].split(':')[1] 

그 요약 파일에있는 모든 쓰레기통을 잡아 : 그래서 내가하고 싶은이 작업은 나에게 압도적 조금 그래서 하나의 텍스트 파일을 처리하고 얻을 내가 원하는 데이터, 예를하기 시작입니다 :이 독서를 할 방법을 잘 및 사이트 (S1, S2)의 N 번호를 포함하는 텍스트 파일의 여러 n 개의 구문 분석 아니라서

SoftBins_str = filter(lambda x: re.search(r'bin',x),fh_d10SumFile_perline) 
for index in range(len(SoftBins_str)): 
    SoftBins_data_str = [l.strip() for l in SoftBins_str[index].split(' ') if l.strip()] 
    SoftBins_data_str.reverse() 
    bin2bin[SoftBins_data_str[0]] = SoftBins_data_str[2] 

은 그럼 내가이 붙어있어. n 개의 텍스트 파일에서이 정보를 가져 와서 메모리에서 처리합니다 (파이썬에서는 가능합니다). csv 출력 파일에 계산으로 출력을 씁니다.

+0

** 적어도 두 개의 요약 파일 **이라고 말하지만 출력 형식은 두 번에 고정되어 있습니까? 또한'Lot :'은 현재'Batch No.'이고'Operation :'은'Test'라고 가정합니다. –

+0

@MartinEvans 예, 맞습니다. –

+0

@SreejithMenon이 질문을 더 자세한 내용과 방법으로 업데이트했습니다. –

답변

1

다음과 같이 시작하면 도움이됩니다. 텍스트 파일은 고정 형식이므로 비교적 쉽게 읽고 파싱 할 수 있습니다. 이 스크립트는 현재 폴더의 모든 텍스트 파일을 검색하고, 배치 이름을 기반으로 사전에 각 파일을 읽고 저장합니다. 따라서 동일한 이름 영역의 모든 배치가 함께 그룹화됩니다.

모든 파일을 처리 한 후에는 각 일괄 처리에 대한 요약을 만들고이를 단일 csv 출력 파일에 기록합니다.

Lot: A2J3 
Operation: Test 
Bin Pass 1 Pass 2 Final Yield %Yield 
Bad 3 1 4 30.8% 
Good 7 2 9 69.2% 

주, 스크립트가 빈 유형의 수를 처리하도록 업데이트되었습니다 다음과 같이 당신에게 탭을주기

from collections import defaultdict 
import glob 
import csv 

batches = defaultdict(list) 

for text_file in glob.glob('*.txt'): 
    with open(text_file) as f_input: 
     rows = [row.strip() for row in f_input] 

    header = [rows[x].split(':')[1].strip() for x in range(1, 6)] 
    bins = {} 

    for yield_info in rows[8:]: 
     s1, s2, total, bin_name = yield_info.split() 
     bins[bin_name] = [int(s1), int(s2), int(total)] 

    batches[header[0]].append(header + [bins]) 


with open('output.csv', 'wb') as f_output: 
    csv_output = csv.writer(f_output, delimiter='\t') 

    for batch, passes in batches.items(): 
     bins_output = defaultdict(lambda: [[], 0]) 
     total_yield = 0 

     for lot, operation, fruit, op_num, quantity, bins in passes: 
      for bin_name, (s1, s2, total) in bins.iteritems(): 
       bins_output[bin_name][0].append(total) 
       bins_output[bin_name][1] += total 
       total_yield += total 

     csv_output.writerows([['Lot:', lot], ['Operation:', operation]]) 
     csv_header = ["Bin"] + ['Pass {}'.format(x) for x in range(1, 1 + len(passes))] + ["Final Yield", "%Yield"]   
     csv_output.writerow(csv_header) 

     for bin_name in sorted(bins_output.keys()): 
      entries, total = bins_output[bin_name] 
      percentage_yield = '{:.1f}%'.format((100.0 * total)/total_yield) 
      csv_output.writerow([bin_name] + entries + [total, percentage_yield]) 

     csv_output.writerow([])  # empty row to separate batches 

csv 파일을 구분.

관련 문제